refactor(random): refactor random string generation (#633)

This commit is contained in:
Luca Steeb
2024-06-24 23:44:03 +01:00
committed by GitHub
parent 1fb8576f7b
commit b6dcb4e7e9
13 changed files with 90 additions and 40 deletions
+2 -2
View File
@@ -7,7 +7,7 @@ import (
"github.com/labstack/echo/v4"
"github.com/hatchet-dev/hatchet/pkg/config/server"
"github.com/hatchet-dev/hatchet/pkg/encryption"
"github.com/hatchet-dev/hatchet/pkg/random"
"github.com/hatchet-dev/hatchet/pkg/repository/prisma/db"
)
@@ -112,7 +112,7 @@ func (s *SessionHelpers) SaveOAuthState(
c echo.Context,
integration string,
) (string, error) {
state, err := encryption.GenerateRandomBytes(16)
state, err := random.Generate(16)
if err != nil {
return "", err
+3 -2
View File
@@ -16,6 +16,7 @@ import (
"github.com/hatchet-dev/hatchet/pkg/config/loader"
"github.com/hatchet-dev/hatchet/pkg/config/server"
"github.com/hatchet-dev/hatchet/pkg/encryption"
"github.com/hatchet-dev/hatchet/pkg/random"
)
var certDir string
@@ -213,13 +214,13 @@ func setupCerts(generated *generatedConfigFiles) error {
func generateKeys(generated *generatedConfigFiles) error {
color.New(color.FgGreen).Printf("Generating encryption keys for Hatchet server\n")
cookieHashKey, err := encryption.GenerateRandomBytes(8)
cookieHashKey, err := random.Generate(8)
if err != nil {
return fmt.Errorf("could not generate hash key for instance: %w", err)
}
cookieBlockKey, err := encryption.GenerateRandomBytes(8)
cookieBlockKey, err := random.Generate(8)
if err != nil {
return fmt.Errorf("could not generate block key for instance: %w", err)
+2 -2
View File
@@ -15,8 +15,8 @@ import (
"github.com/rs/zerolog"
"github.com/hatchet-dev/hatchet/internal/msgqueue"
"github.com/hatchet-dev/hatchet/pkg/encryption"
"github.com/hatchet-dev/hatchet/pkg/logger"
"github.com/hatchet-dev/hatchet/pkg/random"
)
const MAX_RETRY_COUNT = 15
@@ -234,7 +234,7 @@ func (t *MessageQueueImpl) initQueue(sub session, q msgqueue.Queue) (string, err
name := q.Name()
if q.FanoutExchangeKey() != "" {
suffix, err := encryption.GenerateRandomBytes(4)
suffix, err := random.Generate(4)
if err != nil {
t.l.Error().Msgf("error generating random bytes: %v", err)
+4 -4
View File
@@ -14,7 +14,7 @@ import (
"github.com/hatchet-dev/hatchet/internal/msgqueue"
"github.com/hatchet-dev/hatchet/internal/msgqueue/rabbitmq"
"github.com/hatchet-dev/hatchet/pkg/encryption"
"github.com/hatchet-dev/hatchet/pkg/random"
)
func TestMessageQueueIntegration(t *testing.T) {
@@ -34,7 +34,7 @@ func TestMessageQueueIntegration(t *testing.T) {
require.NotNil(t, tq, "task queue implementation should not be nil")
id, _ := encryption.GenerateRandomBytes(4) // nolint: errcheck
id, _ := random.Generate(4) // nolint: errcheck
// Test adding a task to a static queue
staticQueue := msgqueue.EVENT_PROCESSING_QUEUE
@@ -116,7 +116,7 @@ func TestDeadLetteringSuccess(t *testing.T) {
require.NotNil(t, tq, "task queue implementation should not be nil")
id, _ := encryption.GenerateRandomBytes(4) // nolint: errcheck
id, _ := random.Generate(4) // nolint: errcheck
// Test adding a task to a static queue
staticQueue := msgqueue.EVENT_PROCESSING_QUEUE
@@ -174,7 +174,7 @@ func TestDeadLetteringExceedRetriesFailure(t *testing.T) {
require.NotNil(t, tq, "task queue implementation should not be nil")
id, _ := encryption.GenerateRandomBytes(4) // nolint: errcheck
id, _ := random.Generate(4) // nolint: errcheck
// Test adding a task to a static queue
staticQueue := msgqueue.EVENT_PROCESSING_QUEUE
+2 -2
View File
@@ -15,8 +15,8 @@ import (
"github.com/hatchet-dev/hatchet/internal/integrations/vcs"
"github.com/hatchet-dev/hatchet/internal/integrations/vcs/vcsutils"
"github.com/hatchet-dev/hatchet/pkg/client"
"github.com/hatchet-dev/hatchet/pkg/encryption"
"github.com/hatchet-dev/hatchet/pkg/logger"
"github.com/hatchet-dev/hatchet/pkg/random"
"github.com/hatchet-dev/hatchet/pkg/repository"
"github.com/hatchet-dev/hatchet/pkg/worker"
)
@@ -241,7 +241,7 @@ func (w *WorkerImpl) handleStartPullRequest(ctx worker.HatchetContext) error {
return true
})
prSuffix, err := encryption.GenerateRandomBytes(4)
prSuffix, err := random.Generate(4)
if err != nil {
return fmt.Errorf("could not generate random bytes: %w", err)
+3 -3
View File
@@ -12,7 +12,7 @@ import (
"github.com/hatchet-dev/hatchet/internal/testutils"
"github.com/hatchet-dev/hatchet/pkg/auth/cookie"
"github.com/hatchet-dev/hatchet/pkg/config/database"
"github.com/hatchet-dev/hatchet/pkg/encryption"
"github.com/hatchet-dev/hatchet/pkg/random"
)
func TestSessionStoreSave(t *testing.T) {
@@ -63,13 +63,13 @@ func TestSessionStoreGet(t *testing.T) {
}
func newSessionStore(t *testing.T, conf *database.Config, cookieName string) *cookie.UserSessionStore {
hashKey, err := encryption.GenerateRandomBytes(16)
hashKey, err := random.Generate(16)
if err != nil {
t.Fatalf(err.Error())
}
blockKey, err := encryption.GenerateRandomBytes(16)
blockKey, err := random.Generate(16)
if err != nil {
t.Fatalf(err.Error())
+4 -3
View File
@@ -15,6 +15,7 @@ import (
"github.com/hatchet-dev/hatchet/pkg/auth/token"
"github.com/hatchet-dev/hatchet/pkg/config/database"
"github.com/hatchet-dev/hatchet/pkg/encryption"
"github.com/hatchet-dev/hatchet/pkg/random"
"github.com/hatchet-dev/hatchet/pkg/repository"
)
@@ -25,7 +26,7 @@ func TestCreateTenantToken(t *testing.T) { // make sure no cache is used for tes
tenantId := uuid.New().String()
// create the tenant
slugSuffix, err := encryption.GenerateRandomBytes(8)
slugSuffix, err := random.Generate(8)
if err != nil {
t.Fatal(err.Error())
@@ -66,7 +67,7 @@ func TestRevokeTenantToken(t *testing.T) {
tenantId := uuid.New().String()
// create the tenant
slugSuffix, err := encryption.GenerateRandomBytes(8)
slugSuffix, err := random.Generate(8)
if err != nil {
t.Fatal(err.Error())
@@ -126,7 +127,7 @@ func TestRevokeTenantTokenCache(t *testing.T) {
tenantId := uuid.New().String()
// create the tenant
slugSuffix, err := encryption.GenerateRandomBytes(8)
slugSuffix, err := random.Generate(8)
if err != nil {
t.Fatal(err.Error())
+2 -1
View File
@@ -37,6 +37,7 @@ import (
"github.com/hatchet-dev/hatchet/pkg/errors"
"github.com/hatchet-dev/hatchet/pkg/errors/sentry"
"github.com/hatchet-dev/hatchet/pkg/logger"
"github.com/hatchet-dev/hatchet/pkg/random"
"github.com/hatchet-dev/hatchet/pkg/repository/cache"
"github.com/hatchet-dev/hatchet/pkg/repository/metered"
"github.com/hatchet-dev/hatchet/pkg/repository/prisma"
@@ -379,7 +380,7 @@ func GetServerConfigFromConfigfile(dc *database.Config, cf *server.ServerConfigF
return nil, nil, fmt.Errorf("could not get internal tenant: %w", err)
}
tokenSuffix, err := encryption.GenerateRandomBytes(4)
tokenSuffix, err := random.Generate(4)
if err != nil {
return nil, nil, fmt.Errorf("could not generate token suffix: %w", err)
-18
View File
@@ -1,18 +0,0 @@
package encryption
import (
"crypto/rand"
"encoding/hex"
)
// GenerateRandomBytes generates a random string of n bytes.
func GenerateRandomBytes(n int) (string, error) {
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
+22
View File
@@ -0,0 +1,22 @@
package random
import (
"crypto/rand"
"math/big"
)
const letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
// Generate generates a random string of n bytes.
func Generate(n int) (string, error) {
b := make([]byte, n)
for i := 0; i < n; i++ {
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
if err != nil {
return "", err
}
b[i] = letters[num.Int64()]
}
return string(b), nil
}
+42
View File
@@ -0,0 +1,42 @@
package random
import (
"fmt"
"regexp"
"testing"
"github.com/stretchr/testify/assert"
)
func TestGenerateRandomString(t *testing.T) {
type args struct {
n int
}
tests := []struct {
name string
args args
want func(string) bool
wantErr assert.ErrorAssertionFunc
}{{
name: "GenerateRandomString",
args: args{
n: 32,
},
want: func(s string) bool {
if match, err := regexp.MatchString(`^[0-9a-zA-Z]+$`, s); err != nil || !match {
return false
}
return len(s) == 32
},
wantErr: assert.NoError,
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Generate(tt.args.n)
if !tt.wantErr(t, err, fmt.Sprintf("GenerateRandomString(%v)", tt.args.n)) {
return
}
assert.Equalf(t, true, tt.want(got), "GenerateRandomString(%v)", tt.args.n)
})
}
}
+2 -1
View File
@@ -7,6 +7,7 @@ import (
"github.com/steebchen/prisma-client-go/runtime/types"
"github.com/hatchet-dev/hatchet/pkg/encryption"
"github.com/hatchet-dev/hatchet/pkg/random"
"github.com/hatchet-dev/hatchet/pkg/repository/prisma/db"
)
@@ -46,7 +47,7 @@ func NewGithubWebhookCreateOpts(
repoOwner string,
repoName string,
) (opts *CreateGithubWebhookOpts, signingSecret string, err error) {
signingSecret, err = encryption.GenerateRandomBytes(16)
signingSecret, err = random.Generate(16)
if err != nil {
return nil, "", fmt.Errorf("failed to generate signing secret: %s", err.Error())
+2 -2
View File
@@ -6,7 +6,7 @@ import (
"time"
"github.com/hatchet-dev/hatchet/internal/datautils"
"github.com/hatchet-dev/hatchet/pkg/encryption"
"github.com/hatchet-dev/hatchet/pkg/random"
"github.com/hatchet-dev/hatchet/pkg/repository/prisma/db"
"github.com/hatchet-dev/hatchet/pkg/repository/prisma/dbsqlc"
"github.com/hatchet-dev/hatchet/pkg/repository/prisma/sqlchelpers"
@@ -224,7 +224,7 @@ func GetCreateWorkflowRunOptsFromSchedule(
}
func getWorkflowRunDisplayName(workflowName string) string {
workflowSuffix, _ := encryption.GenerateRandomBytes(3)
workflowSuffix, _ := random.Generate(3)
return workflowName + "-" + workflowSuffix
}