Skip to content

Commit

Permalink
chore: move random to a standalone package
Browse files Browse the repository at this point in the history
Signed-off-by: Radoslav Dimitrov <radoslav@stacklok.com>
  • Loading branch information
rdimitrov committed Sep 29, 2023
1 parent a335ad9 commit 7a9f85a
Show file tree
Hide file tree
Showing 14 changed files with 71 additions and 69 deletions.
3 changes: 2 additions & 1 deletion cmd/cli/app/auth/auth_login.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import (
"github.com/stacklok/mediator/internal/config"
mcrypto "github.com/stacklok/mediator/internal/crypto"
"github.com/stacklok/mediator/internal/util"
"github.com/stacklok/mediator/internal/util/rand"
pb "github.com/stacklok/mediator/pkg/api/protobuf/go/mediator/v1"
)

Expand Down Expand Up @@ -94,7 +95,7 @@ will be saved to $XDG_CONFIG_HOME/mediator/credentials.json`,
}

// Get random port
port, err := util.GetRandomPort()
port, err := rand.GetRandomPort()
util.ExitNicelyOnError(err, "Error getting random port")

parsedURL, err = url.Parse(fmt.Sprintf("http://localhost:%v", port))
Expand Down
3 changes: 2 additions & 1 deletion cmd/cli/app/provider/provider_enroll.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import (

ghclient "github.com/stacklok/mediator/internal/providers/github"
"github.com/stacklok/mediator/internal/util"
"github.com/stacklok/mediator/internal/util/rand"
pb "github.com/stacklok/mediator/pkg/api/protobuf/go/mediator/v1"
)

Expand Down Expand Up @@ -157,7 +158,7 @@ actions such as adding repositories.`,
fmt.Println("Provider enrolled successfully")
} else {
// Get random port
port, err := util.GetRandomPort()
port, err := rand.GetRandomPort()
util.ExitNicelyOnError(err, "Error getting random port")

resp, err := client.GetAuthorizationURL(ctx, &pb.GetAuthorizationURLRequest{
Expand Down
6 changes: 3 additions & 3 deletions internal/auth/jwauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ import (
"github.com/stretchr/testify/require"

mockjwt "github.com/stacklok/mediator/internal/auth/mock"
"github.com/stacklok/mediator/internal/util"
"github.com/stacklok/mediator/internal/util/rand"
)

func TestParseAndValidate(t *testing.T) {
t.Parallel()

jwks := jwk.NewSet()
privateKey, publicKey := util.RandomKeypair(2048)
privateKey, publicKey := rand.RandomKeypair(2048)
privateJwk, _ := jwk.FromRaw(privateKey)
err := privateJwk.Set(jwk.KeyIDKey, `mykey`)
require.NoError(t, err, "failed to setup private key ID")
Expand Down Expand Up @@ -83,7 +83,7 @@ func TestParseAndValidate(t *testing.T) {
{
name: "Invalid signature",
buildToken: func() string {
otherKey, _ := util.RandomKeypair(2048)
otherKey, _ := rand.RandomKeypair(2048)
otherJwk, _ := jwk.FromRaw(otherKey)
err = otherJwk.Set(jwk.KeyIDKey, `otherKey`)
require.NoError(t, err, "failed to setup signing key ID")
Expand Down
4 changes: 2 additions & 2 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import (
"github.com/stretchr/testify/require"

"github.com/stacklok/mediator/internal/config"
"github.com/stacklok/mediator/internal/util"
"github.com/stacklok/mediator/internal/util/rand"
)

func TestReadValidConfig(t *testing.T) {
Expand Down Expand Up @@ -186,7 +186,7 @@ func TestReadAuthConfig(t *testing.T) {
AccessTokenPrivateKey: filepath.Join(tmpdir, "access_token_private.pem"),
AccessTokenPublicKey: filepath.Join(tmpdir, "access_token_public.pem"),
}
err := util.RandomKeypairFile(2048, cfg.AccessTokenPrivateKey, cfg.AccessTokenPublicKey)
err := rand.RandomKeypairFile(2048, cfg.AccessTokenPrivateKey, cfg.AccessTokenPublicKey)
if err != nil {
t.Fatalf("Error generating access token key pair: %v", err)
}
Expand Down
10 changes: 5 additions & 5 deletions internal/controlplane/handlers_githubwebhooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ import (
mockdb "github.com/stacklok/mediator/database/mock"
"github.com/stacklok/mediator/internal/db"
"github.com/stacklok/mediator/internal/engine"
"github.com/stacklok/mediator/internal/util"
"github.com/stacklok/mediator/internal/util/rand"
)

// MockClient is a mock implementation of the GitHub client.
Expand Down Expand Up @@ -156,7 +156,7 @@ func (s *UnitTestSuite) TestHandleWebHookPing() {
srv.evt.Register(engine.InternalEntityEventTopic, pq.pass)

hook := srv.HandleGitHubWebHook()
port, err := util.GetRandomPort()
port, err := rand.GetRandomPort()
require.NoError(t, err, "failed to get random port")

addr := fmt.Sprintf("localhost:%d", port)
Expand Down Expand Up @@ -211,7 +211,7 @@ func (s *UnitTestSuite) TestHandleWebHookUnexistentRepository() {
Return(db.Repository{}, sql.ErrNoRows)

hook := srv.HandleGitHubWebHook()
port, err := util.GetRandomPort()
port, err := rand.GetRandomPort()
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -293,7 +293,7 @@ func (s *UnitTestSuite) TestHandleWebHookRepository() {
}, nil)

hook := srv.HandleGitHubWebHook()
port, err := util.GetRandomPort()
port, err := rand.GetRandomPort()
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -368,7 +368,7 @@ func (s *UnitTestSuite) TestHandleWebHookUnexistentRepoPackage() {
Return(db.Repository{}, sql.ErrNoRows)

hook := srv.HandleGitHubWebHook()
port, err := util.GetRandomPort()
port, err := rand.GetRandomPort()
if err != nil {
t.Fatal(err)
}
Expand Down
6 changes: 3 additions & 3 deletions internal/db/groups_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import (

"github.com/stretchr/testify/require"

"github.com/stacklok/mediator/internal/util"
"github.com/stacklok/mediator/internal/util/rand"
)

func createRandomGroup(t *testing.T, org int32) Group {
Expand All @@ -37,7 +37,7 @@ func createRandomGroup(t *testing.T, org int32) Group {
seed := time.Now().UnixNano()
arg := CreateGroupParams{
OrganizationID: org,
Name: util.RandomName(seed),
Name: rand.RandomName(seed),
}

group, err := testQueries.CreateGroup(context.Background(), arg)
Expand Down Expand Up @@ -115,7 +115,7 @@ func TestUpdateGroup(t *testing.T) {
arg := UpdateGroupParams{
ID: group1.ID,
OrganizationID: org.ID,
Name: util.RandomName(seed),
Name: rand.RandomName(seed),
}

group2, err := testQueries.UpdateGroup(context.Background(), arg)
Expand Down
10 changes: 5 additions & 5 deletions internal/db/organizations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import (

"github.com/stretchr/testify/require"

"github.com/stacklok/mediator/internal/util"
"github.com/stacklok/mediator/internal/util/rand"
)

// A helper function to create a random organization
Expand All @@ -38,8 +38,8 @@ func createRandomOrganization(t *testing.T) Organization {

seed := time.Now().UnixNano()
arg := CreateOrganizationParams{
Name: util.RandomName(seed),
Company: util.RandomName(seed),
Name: rand.RandomName(seed),
Company: rand.RandomName(seed),
}

organization, err := testQueries.CreateOrganization(context.Background(), arg)
Expand Down Expand Up @@ -93,8 +93,8 @@ func TestUpdateOrganization(t *testing.T) {

arg := UpdateOrganizationParams{
ID: organization1.ID,
Name: util.RandomName(seed),
Company: util.RandomName(seed),
Name: rand.RandomName(seed),
Company: rand.RandomName(seed),
}

organization2, err := testQueries.UpdateOrganization(context.Background(), arg)
Expand Down
4 changes: 2 additions & 2 deletions internal/db/providers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import (

"github.com/stretchr/testify/require"

"github.com/stacklok/mediator/internal/util"
"github.com/stacklok/mediator/internal/util/rand"
)

func createRandomProvider(t *testing.T, groupID int32) Provider {
Expand All @@ -38,7 +38,7 @@ func createRandomProvider(t *testing.T, groupID int32) Provider {
seed := time.Now().UnixNano()

prov, err := testQueries.CreateProvider(context.Background(), CreateProviderParams{
Name: util.RandomName(seed),
Name: rand.RandomName(seed),
GroupID: groupID,
Implements: []ProviderType{ProviderTypeGithub, ProviderTypeGit},
Definition: json.RawMessage("{}"),
Expand Down
14 changes: 7 additions & 7 deletions internal/db/repositories_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import (

"github.com/stretchr/testify/require"

"github.com/stacklok/mediator/internal/util"
"github.com/stacklok/mediator/internal/util/rand"
)

type RepositoryOption func(*CreateRepositoryParams)
Expand All @@ -54,14 +54,14 @@ func createRandomRepository(t *testing.T, group int32, prov string, opts ...Repo
arg := CreateRepositoryParams{
Provider: prov,
GroupID: group,
RepoOwner: util.RandomName(seed),
RepoName: util.RandomName(seed),
RepoID: int32(util.RandomInt(0, 1000, seed)),
RepoOwner: rand.RandomName(seed),
RepoName: rand.RandomName(seed),
RepoID: int32(rand.RandomInt(0, 1000, seed)),
IsPrivate: false,
IsFork: false,
WebhookID: sql.NullInt32{Int32: int32(util.RandomInt(0, 1000, seed)), Valid: true},
WebhookUrl: util.RandomURL(seed),
DeployUrl: util.RandomURL(seed),
WebhookID: sql.NullInt32{Int32: int32(rand.RandomInt(0, 1000, seed)), Valid: true},
WebhookUrl: rand.RandomURL(seed),
DeployUrl: rand.RandomURL(seed),
}
// Allow arbitrary fixups to the Repository
for _, o := range opts {
Expand Down
6 changes: 3 additions & 3 deletions internal/db/roles_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import (

"github.com/stretchr/testify/require"

"github.com/stacklok/mediator/internal/util"
"github.com/stacklok/mediator/internal/util/rand"
)

// A helper function to create a random role
Expand All @@ -38,7 +38,7 @@ func createRandomRole(t *testing.T, org int32) Role {
seed := time.Now().UnixNano()
arg := CreateRoleParams{
OrganizationID: org,
Name: util.RandomName(seed),
Name: rand.RandomName(seed),
}

role, err := testQueries.CreateRole(context.Background(), arg)
Expand Down Expand Up @@ -93,7 +93,7 @@ func TestUpdateRole(t *testing.T) {
arg := UpdateRoleParams{
ID: role1.ID,
OrganizationID: org.ID,
Name: util.RandomName(seed),
Name: rand.RandomName(seed),
IsAdmin: true,
}

Expand Down
10 changes: 5 additions & 5 deletions internal/db/users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import (

"github.com/stretchr/testify/require"

"github.com/stacklok/mediator/internal/util"
"github.com/stacklok/mediator/internal/util/rand"
)

func stringToNullString(s string) sql.NullString {
Expand All @@ -45,10 +45,10 @@ func createRandomUser(t *testing.T, org Organization) User {

arg := CreateUserParams{
OrganizationID: org.ID,
IdentitySubject: util.RandomString(10, seed),
Email: stringToNullString(util.RandomEmail(seed)),
FirstName: stringToNullString(util.RandomName(seed)),
LastName: stringToNullString(util.RandomName(seed)),
IdentitySubject: rand.RandomString(10, seed),
Email: stringToNullString(rand.RandomEmail(seed)),
FirstName: stringToNullString(rand.RandomName(seed)),
LastName: stringToNullString(rand.RandomName(seed)),
}

user, err := testQueries.CreateUser(context.Background(), arg)
Expand Down
22 changes: 0 additions & 22 deletions internal/util/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import (
"io"
"io/fs"
"log"
"net"
"os"
"path/filepath"
"strconv"
Expand Down Expand Up @@ -251,27 +250,6 @@ func GetAppContext() (context.Context, context.CancelFunc) {
return ctx, cancel
}

// GetRandomPort returns a random port number.
// The binding address should not need to be configurable
// as this is a short lived operation just to disover a random available port.
// Note that there is a possible race condition here if another process binds
// to the same port between the time we discover it and the time we use it.
// This is unlikely to happen in practice, but if it does, the user will
// need to retry the command.
// Marking a nosec here because we want this to listen on all addresses to
// ensure a reliable connection chance for the client. This is based on lessons
// learned from the sigstore CLI.
func GetRandomPort() (int, error) {
listener, err := net.Listen("tcp", ":0") // #nosec
if err != nil {
return 0, err
}
defer listener.Close()

port := listener.Addr().(*net.TCPAddr).Port
return port, nil
}

// WriteToFile writes the content to a file if the out parameter is not empty.
func WriteToFile(out string, content []byte, perms fs.FileMode) error {
if out != "" {
Expand Down
30 changes: 26 additions & 4 deletions internal/util/random.go → internal/util/rand/random.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,18 @@
// It does make a good example of how to use the generated client code
// for others to use as a reference.

// Package util contains utility functions largely for unit testing.
// WARNING: Do not use the functions in this package that generate random / seeds
// Package rand contains utility functions largely for unit testing.
// WARNING: Do not use the functions in this package that generate rand / seeds
// for any security related purposes, outside of testing.
package util
package rand

import (
crand "crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"math/rand"
"net"
"os"
"path/filepath"
)
Expand Down Expand Up @@ -120,7 +121,7 @@ func getRandomChar(r *rand.Rand, charset string) byte {
return charset[r.Intn(len(charset))]
}

// RandomKeypair returns a random RSA keypair
// RandomKeypair returns a rand RSA keypair
func RandomKeypair(length int) (*rsa.PrivateKey, *rsa.PublicKey) {
privateKey, err := rsa.GenerateKey(crand.Reader, length)
if err != nil {
Expand Down Expand Up @@ -198,3 +199,24 @@ func RandomPrivateKeyFile(length int, filePath string) error {

return nil
}

// GetRandomPort returns a random port number.
// The binding address should not need to be configurable
// as this is a short-lived operation just to discover a random available port.
// Note that there is a possible race condition here if another process binds
// to the same port between the time we discover it and the time we use it.
// This is unlikely to happen in practice, but if it does, the user will
// need to retry the command.
// Marking a nosec here because we want this to listen on all addresses to
// ensure a reliable connection chance for the client. This is based on lessons
// learned from the sigstore CLI.
func GetRandomPort() (int, error) {
listener, err := net.Listen("tcp", ":0") // #nosec
if err != nil {
return 0, err
}
defer listener.Close()

port := listener.Addr().(*net.TCPAddr).Port
return port, nil
}
Loading

0 comments on commit 7a9f85a

Please sign in to comment.