From b362a073298ad772b570c8aebbd1919daeef6963 Mon Sep 17 00:00:00 2001 From: Marten Seemann Date: Fri, 6 Jun 2025 13:02:38 +0800 Subject: [PATCH] use new randutil functions without error return values --- acme/api/order.go | 8 +- acme/db/nosql/account.go | 6 +- acme/db/nosql/authz.go | 6 +- acme/db/nosql/certificate.go | 9 +- acme/db/nosql/challenge.go | 6 +- acme/db/nosql/eab.go | 17 +--- acme/db/nosql/nonce.go | 7 +- acme/db/nosql/nosql.go | 8 +- acme/db/nosql/order.go | 13 +-- authority/admin/api/webhook.go | 14 +-- authority/admin/db/nosql/admin.go | 6 +- authority/admin/db/nosql/nosql.go | 8 +- authority/admin/db/nosql/provisioner.go | 6 +- authority/authorize_test.go | 21 +---- authority/provisioner/nebula_test.go | 10 +-- authority/provisioner/utils_test.go | 114 +++++------------------- authority/provisioner/x5c_test.go | 16 +--- authority/ssh.go | 7 +- ca/adminClient.go | 5 +- ca/bootstrap_test.go | 6 +- ca/ca_test.go | 12 +-- ca/client.go | 9 +- ca/provisioner.go | 12 +-- ca/tls_test.go | 5 +- cas/stepcas/jwk_issuer.go | 5 +- cas/stepcas/stepcas_test.go | 5 +- cas/stepcas/x5c_issuer.go | 6 +- commands/onboard.go | 5 +- go.mod | 5 +- go.sum | 10 +-- middleware/requestid/requestid.go | 11 +-- scep/authority_test.go | 19 ++-- test/integration/requestid_test.go | 7 +- 33 files changed, 80 insertions(+), 324 deletions(-) diff --git a/acme/api/order.go b/acme/api/order.go index a75a4d84b..97a5418fd 100644 --- a/acme/api/order.go +++ b/acme/api/order.go @@ -321,11 +321,7 @@ func newAuthorization(ctx context.Context, az *acme.Authorization) error { chTypes := challengeTypes(az) - var err error - az.Token, err = randutil.Alphanumeric(32) - if err != nil { - return acme.WrapErrorISE(err, "error generating random alphanumeric ID") - } + az.Token = randutil.Alphanumeric(32) db := acme.MustDatabaseFromContext(ctx) prov := acme.MustProvisionerFromContext(ctx) @@ -378,7 +374,7 @@ func newAuthorization(ctx context.Context, az *acme.Authorization) error { } az.Challenges = append(az.Challenges, ch) } - if err = db.CreateAuthorization(ctx, az); err != nil { + if err := db.CreateAuthorization(ctx, az); err != nil { return acme.WrapErrorISE(err, "error creating authorization") } return nil diff --git a/acme/db/nosql/account.go b/acme/db/nosql/account.go index 9b03db814..ad8529ecc 100644 --- a/acme/db/nosql/account.go +++ b/acme/db/nosql/account.go @@ -86,11 +86,7 @@ func (db *DB) GetAccountByKeyID(ctx context.Context, kid string) (*acme.Account, // CreateAccount imlements the AcmeDB.CreateAccount interface. func (db *DB) CreateAccount(ctx context.Context, acc *acme.Account) error { - var err error - acc.ID, err = randID() - if err != nil { - return err - } + acc.ID = randID() dba := &dbAccount{ ID: acc.ID, diff --git a/acme/db/nosql/authz.go b/acme/db/nosql/authz.go index be3b0fbbd..c7e4b2c43 100644 --- a/acme/db/nosql/authz.go +++ b/acme/db/nosql/authz.go @@ -78,11 +78,7 @@ func (db *DB) GetAuthorization(ctx context.Context, id string) (*acme.Authorizat // CreateAuthorization creates an entry in the database for the Authorization. // Implements the acme.DB.CreateAuthorization interface. func (db *DB) CreateAuthorization(ctx context.Context, az *acme.Authorization) error { - var err error - az.ID, err = randID() - if err != nil { - return err - } + az.ID = randID() chIDs := make([]string, len(az.Challenges)) for i, ch := range az.Challenges { diff --git a/acme/db/nosql/certificate.go b/acme/db/nosql/certificate.go index 35c552465..e8e9dc3b3 100644 --- a/acme/db/nosql/certificate.go +++ b/acme/db/nosql/certificate.go @@ -28,11 +28,7 @@ type dbSerial struct { // CreateCertificate creates and stores an ACME certificate type. func (db *DB) CreateCertificate(ctx context.Context, cert *acme.Certificate) error { - var err error - cert.ID, err = randID() - if err != nil { - return err - } + cert.ID = randID() leaf := pem.EncodeToMemory(&pem.Block{ Type: "CERTIFICATE", @@ -54,8 +50,7 @@ func (db *DB) CreateCertificate(ctx context.Context, cert *acme.Certificate) err Intermediates: intermediates, CreatedAt: time.Now().UTC(), } - err = db.save(ctx, cert.ID, dbch, nil, "certificate", certTable) - if err != nil { + if err := db.save(ctx, cert.ID, dbch, nil, "certificate", certTable); err != nil { return err } diff --git a/acme/db/nosql/challenge.go b/acme/db/nosql/challenge.go index e7c9aa295..317c81af4 100644 --- a/acme/db/nosql/challenge.go +++ b/acme/db/nosql/challenge.go @@ -48,11 +48,7 @@ func (db *DB) getDBChallenge(_ context.Context, id string) (*dbChallenge, error) // CreateChallenge creates a new ACME challenge data structure in the database. // Implements acme.DB.CreateChallenge interface. func (db *DB) CreateChallenge(ctx context.Context, ch *acme.Challenge) error { - var err error - ch.ID, err = randID() - if err != nil { - return errors.Wrap(err, "error generating random id for ACME challenge") - } + ch.ID = randID() dbch := &dbChallenge{ ID: ch.ID, diff --git a/acme/db/nosql/eab.go b/acme/db/nosql/eab.go index e2a437ddf..0a4e0f582 100644 --- a/acme/db/nosql/eab.go +++ b/acme/db/nosql/eab.go @@ -2,11 +2,12 @@ package nosql import ( "context" - "crypto/rand" "encoding/json" "sync" "time" + "go.step.sm/crypto/randutil" + "github.com/pkg/errors" "github.com/smallstep/certificates/acme" @@ -57,22 +58,12 @@ func (db *DB) CreateExternalAccountKey(ctx context.Context, provisionerID, refer externalAccountKeyMutex.Lock() defer externalAccountKeyMutex.Unlock() - keyID, err := randID() - if err != nil { - return nil, err - } - - random := make([]byte, 32) - _, err = rand.Read(random) - if err != nil { - return nil, err - } - + keyID := randID() dbeak := &dbExternalAccountKey{ ID: keyID, ProvisionerID: provisionerID, Reference: reference, - HmacKey: random, + HmacKey: randutil.Bytes(32), CreatedAt: clock.Now(), } diff --git a/acme/db/nosql/nonce.go b/acme/db/nosql/nonce.go index af85b1838..40566fa08 100644 --- a/acme/db/nosql/nonce.go +++ b/acme/db/nosql/nonce.go @@ -21,12 +21,7 @@ type dbNonce struct { // CreateNonce creates, stores, and returns an ACME replay-nonce. // Implements the acme.DB interface. func (db *DB) CreateNonce(ctx context.Context) (acme.Nonce, error) { - _id, err := randID() - if err != nil { - return "", err - } - - id := base64.RawURLEncoding.EncodeToString([]byte(_id)) + id := base64.RawURLEncoding.EncodeToString([]byte(randID())) n := &dbNonce{ ID: id, CreatedAt: clock.Now(), diff --git a/acme/db/nosql/nosql.go b/acme/db/nosql/nosql.go index b2921f55e..29fda32e7 100644 --- a/acme/db/nosql/nosql.go +++ b/acme/db/nosql/nosql.go @@ -86,12 +86,8 @@ func (db *DB) save(_ context.Context, id string, nu, old interface{}, typ string var idLen = 32 -func randID() (val string, err error) { - val, err = randutil.Alphanumeric(idLen) - if err != nil { - return "", errors.Wrap(err, "error generating random alphanumeric ID") - } - return val, nil +func randID() string { + return randutil.Alphanumeric(idLen) } // Clock that returns time in UTC rounded to seconds. diff --git a/acme/db/nosql/order.go b/acme/db/nosql/order.go index 983fbe8d5..edce0e0b6 100644 --- a/acme/db/nosql/order.go +++ b/acme/db/nosql/order.go @@ -75,11 +75,7 @@ func (db *DB) GetOrder(ctx context.Context, id string) (*acme.Order, error) { // CreateOrder creates ACME Order resources and saves them to the DB. func (db *DB) CreateOrder(ctx context.Context, o *acme.Order) error { - var err error - o.ID, err = randID() - if err != nil { - return err - } + o.ID = randID() now := clock.Now() dbo := &dbOrder{ @@ -98,11 +94,8 @@ func (db *DB) CreateOrder(ctx context.Context, o *acme.Order) error { return err } - _, err = db.updateAddOrderIDs(ctx, o.AccountID, false, o.ID) - if err != nil { - return err - } - return nil + _, err := db.updateAddOrderIDs(ctx, o.AccountID, false, o.ID) + return err } // UpdateOrder saves an updated ACME Order to the database. diff --git a/authority/admin/api/webhook.go b/authority/admin/api/webhook.go index e004c4010..d34380366 100644 --- a/authority/admin/api/webhook.go +++ b/authority/admin/api/webhook.go @@ -90,12 +90,7 @@ func (war *webhookAdminResponder) CreateProvisionerWebhook(w http.ResponseWriter return } - id, err := randutil.UUIDv4() - if err != nil { - render.Error(w, r, admin.WrapErrorISE(err, "error generating webhook id")) - return - } - newWebhook.Id = id + newWebhook.Id = randutil.UUIDv4() // verify the name is unique for _, wh := range prov.Webhooks { @@ -106,12 +101,7 @@ func (war *webhookAdminResponder) CreateProvisionerWebhook(w http.ResponseWriter } } - secret, err := randutil.Bytes(64) - if err != nil { - render.Error(w, r, admin.WrapErrorISE(err, "error generating webhook secret")) - return - } - newWebhook.Secret = base64.StdEncoding.EncodeToString(secret) + newWebhook.Secret = base64.StdEncoding.EncodeToString(randutil.Bytes(64)) prov.Webhooks = append(prov.Webhooks, newWebhook) diff --git a/authority/admin/db/nosql/admin.go b/authority/admin/db/nosql/admin.go index 6e7aab669..7db6195c3 100644 --- a/authority/admin/db/nosql/admin.go +++ b/authority/admin/db/nosql/admin.go @@ -130,11 +130,7 @@ func (db *DB) GetAdmins(context.Context) ([]*linkedca.Admin, error) { // CreateAdmin stores a new admin to the database. func (db *DB) CreateAdmin(ctx context.Context, adm *linkedca.Admin) error { - var err error - adm.Id, err = randID() - if err != nil { - return admin.WrapErrorISE(err, "error generating random id for admin") - } + adm.Id = randID() adm.AuthorityId = db.authorityID dba := &dbAdmin{ diff --git a/authority/admin/db/nosql/nosql.go b/authority/admin/db/nosql/nosql.go index 02acf72a2..4dcdd3652 100644 --- a/authority/admin/db/nosql/nosql.go +++ b/authority/admin/db/nosql/nosql.go @@ -70,13 +70,7 @@ func (db *DB) save(_ context.Context, id string, nu, old interface{}, typ string } } -func randID() (val string, err error) { - val, err = randutil.UUIDv4() - if err != nil { - return "", errors.Wrap(err, "error generating random alphanumeric ID") - } - return val, nil -} +func randID() string { return randutil.UUIDv4() } // Clock that returns time in UTC rounded to seconds. type Clock struct{} diff --git a/authority/admin/db/nosql/provisioner.go b/authority/admin/db/nosql/provisioner.go index e3c26b18c..81645c705 100644 --- a/authority/admin/db/nosql/provisioner.go +++ b/authority/admin/db/nosql/provisioner.go @@ -160,11 +160,7 @@ func (db *DB) GetProvisioners(_ context.Context) ([]*linkedca.Provisioner, error // CreateProvisioner stores a new provisioner to the database. func (db *DB) CreateProvisioner(ctx context.Context, prov *linkedca.Provisioner) error { - var err error - prov.Id, err = randID() - if err != nil { - return admin.WrapErrorISE(err, "error generating random id for provisioner") - } + prov.Id = randID() details, err := json.Marshal(prov.Details.GetData()) if err != nil { diff --git a/authority/authorize_test.go b/authority/authorize_test.go index f7287e7a5..827e8a68a 100644 --- a/authority/authorize_test.go +++ b/authority/authorize_test.go @@ -66,17 +66,12 @@ func generateToken(sub, iss, aud string, sans []string, iat time.Time, jwk *jose return "", err } - id, err := randutil.ASCII(64) - if err != nil { - return "", err - } - claims := struct { jose.Claims SANS []string `json:"sans"` }{ Claims: jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: sub, Issuer: iss, IssuedAt: jose.NewNumericDate(iat), @@ -103,14 +98,9 @@ func generateCustomToken(sub, iss, aud string, jwk *jose.JSONWebKey, extraHeader return "", err } - id, err := randutil.ASCII(64) - if err != nil { - return "", err - } - iat := time.Now() claims := jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: sub, Issuer: iss, IssuedAt: jose.NewNumericDate(iat), @@ -967,17 +957,12 @@ func generateSSHToken(sub, iss, aud string, iat time.Time, sshOpts *provisioner. return "", err } - id, err := randutil.ASCII(64) - if err != nil { - return "", err - } - claims := struct { jose.Claims Step *stepPayload `json:"step,omitempty"` }{ Claims: jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: sub, Issuer: iss, IssuedAt: jose.NewNumericDate(iat), diff --git a/authority/provisioner/nebula_test.go b/authority/provisioner/nebula_test.go index 3e2d9780a..d6f8b9efb 100644 --- a/authority/provisioner/nebula_test.go +++ b/authority/provisioner/nebula_test.go @@ -254,15 +254,12 @@ func mustNebulaToken(t *testing.T, sub, iss, aud string, iat time.Time, sans []s sig, err := jose.NewSigner(jose.SigningKey{Algorithm: algorithm, Key: key}, so) require.NoError(t, err) - id, err := randutil.ASCII(64) - require.NoError(t, err) - claims := struct { jose.Claims SANS []string `json:"sans"` }{ Claims: jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: sub, Issuer: iss, IssuedAt: jose.NewNumericDate(iat), @@ -290,15 +287,12 @@ func mustNebulaSSHToken(t *testing.T, sub, iss, aud string, iat time.Time, opts sig, err := jose.NewSigner(jose.SigningKey{Algorithm: algorithm, Key: key}, so) require.NoError(t, err) - id, err := randutil.ASCII(64) - require.NoError(t, err) - claims := struct { jose.Claims Step *stepPayload `json:"step,omitempty"` }{ Claims: jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: sub, Issuer: iss, IssuedAt: jose.NewNumericDate(iat), diff --git a/authority/provisioner/utils_test.go b/authority/provisioner/utils_test.go index 09e069728..1e9644688 100644 --- a/authority/provisioner/utils_test.go +++ b/authority/provisioner/utils_test.go @@ -123,17 +123,13 @@ func encryptJSONWebKey(jwk *jose.JSONWebKey) (*jose.JSONWebEncryption, error) { if err != nil { return nil, err } - salt, err := randutil.Salt(jose.PBKDF2SaltSize) - if err != nil { - return nil, err - } opts := new(jose.EncrypterOptions) opts.WithContentType(jose.ContentType("jwk+json")) recipient := jose.Recipient{ Algorithm: jose.PBES2_HS256_A128KW, Key: []byte("password"), PBES2Count: jose.PBKDF2Iterations, - PBES2Salt: salt, + PBES2Salt: randutil.Salt(jose.PBKDF2SaltSize), } encrypter, err := jose.NewEncrypter(jose.DefaultEncAlgorithm, recipient, opts) if err != nil { @@ -159,10 +155,6 @@ func decryptJSONWebKey(key string) (*jose.JSONWebKey, error) { } func generateJWK() (*JWK, error) { - name, err := randutil.Alphanumeric(10) - if err != nil { - return nil, err - } jwk, err := generateJSONWebKey() if err != nil { return nil, err @@ -178,7 +170,7 @@ func generateJWK() (*JWK, error) { } p := &JWK{ - Name: name, + Name: randutil.Alphanumeric(10), Type: "JWK", Key: &public, EncryptedKey: encrypted, @@ -226,10 +218,6 @@ func generateK8sSA(inputPubKey interface{}) (*K8sSA, error) { } func generateSSHPOP() (*SSHPOP, error) { - name, err := randutil.Alphanumeric(10) - if err != nil { - return nil, err - } userB, err := os.ReadFile("./testdata/certs/ssh_user_ca_key.pub") if err != nil { return nil, err @@ -248,7 +236,7 @@ func generateSSHPOP() (*SSHPOP, error) { } p := &SSHPOP{ - Name: name, + Name: randutil.Alphanumeric(10), Type: "SSHPOP", Claims: &globalProvisionerClaims, sshPubKeys: &SSHKeys{ @@ -277,10 +265,6 @@ M46l92gdOozT -----END CERTIFICATE-----`) } - name, err := randutil.Alphanumeric(10) - if err != nil { - return nil, err - } rootPool := x509.NewCertPool() var ( @@ -299,12 +283,13 @@ M46l92gdOozT rootPool.AddCert(cert) } p := &X5C{ - Name: name, + Name: randutil.Alphanumeric(10), Type: "X5C", Roots: root, Claims: &globalProvisionerClaims, rootPool: rootPool, } + var err error p.ctl, err = NewController(p, p.Claims, Config{ Audiences: testAudiences, }, nil) @@ -312,30 +297,18 @@ M46l92gdOozT } func generateOIDC() (*OIDC, error) { - name, err := randutil.Alphanumeric(10) - if err != nil { - return nil, err - } - clientID, err := randutil.Alphanumeric(10) - if err != nil { - return nil, err - } - issuer, err := randutil.Alphanumeric(10) - if err != nil { - return nil, err - } jwk, err := generateJSONWebKey() if err != nil { return nil, err } p := &OIDC{ - Name: name, + Name: randutil.Alphanumeric(10), Type: "OIDC", - ClientID: clientID, + ClientID: randutil.Alphanumeric(10), ConfigurationEndpoint: "https://example.com/.well-known/openid-configuration", Claims: &globalProvisionerClaims, configuration: openIDConfiguration{ - Issuer: issuer, + Issuer: randutil.Alphanumeric(10), JWKSetURI: "https://example.com/.well-known/jwks", }, keyStore: &keyStore{ @@ -350,14 +323,7 @@ func generateOIDC() (*OIDC, error) { } func generateGCP() (*GCP, error) { - name, err := randutil.Alphanumeric(10) - if err != nil { - return nil, err - } - serviceAccount, err := randutil.Alphanumeric(10) - if err != nil { - return nil, err - } + name := randutil.Alphanumeric(10) jwk, err := generateJSONWebKey() if err != nil { return nil, err @@ -365,7 +331,7 @@ func generateGCP() (*GCP, error) { p := &GCP{ Type: "GCP", Name: name, - ServiceAccounts: []string{serviceAccount}, + ServiceAccounts: []string{randutil.Alphanumeric(10)}, Claims: &globalProvisionerClaims, DisableSSHCAHost: &DefaultDisableSSHCAHost, DisableSSHCAUser: &DefaultDisableSSHCAUser, @@ -382,14 +348,7 @@ func generateGCP() (*GCP, error) { } func generateAWS() (*AWS, error) { - name, err := randutil.Alphanumeric(10) - if err != nil { - return nil, err - } - accountID, err := randutil.Alphanumeric(10) - if err != nil { - return nil, err - } + name := randutil.Alphanumeric(10) block, _ := pem.Decode([]byte(awsTestCertificate)) if block == nil || block.Type != "CERTIFICATE" { return nil, errors.New("error decoding AWS certificate") @@ -401,7 +360,7 @@ func generateAWS() (*AWS, error) { p := &AWS{ Type: "AWS", Name: name, - Accounts: []string{accountID}, + Accounts: []string{randutil.Alphanumeric(10)}, Claims: &globalProvisionerClaims, IMDSVersions: []string{"v2", "v1"}, config: &awsConfig{ @@ -490,14 +449,7 @@ func generateAWSWithServer() (*AWS, *httptest.Server, error) { } func generateAWSV1Only() (*AWS, error) { - name, err := randutil.Alphanumeric(10) - if err != nil { - return nil, err - } - accountID, err := randutil.Alphanumeric(10) - if err != nil { - return nil, err - } + name := randutil.Alphanumeric(10) block, _ := pem.Decode([]byte(awsTestCertificate)) if block == nil || block.Type != "CERTIFICATE" { return nil, errors.New("error decoding AWS certificate") @@ -509,7 +461,7 @@ func generateAWSV1Only() (*AWS, error) { p := &AWS{ Type: "AWS", Name: name, - Accounts: []string{accountID}, + Accounts: []string{randutil.Alphanumeric(10)}, Claims: &globalProvisionerClaims, IMDSVersions: []string{"v1"}, config: &awsConfig{ @@ -583,21 +535,14 @@ func generateAWSWithServerV1Only() (*AWS, *httptest.Server, error) { } func generateAzure() (*Azure, error) { - name, err := randutil.Alphanumeric(10) - if err != nil { - return nil, err - } - tenantID, err := randutil.Alphanumeric(10) - if err != nil { - return nil, err - } + tenantID := randutil.Alphanumeric(10) jwk, err := generateJSONWebKey() if err != nil { return nil, err } p := &Azure{ Type: "Azure", - Name: name, + Name: randutil.Alphanumeric(10), TenantID: tenantID, Audience: azureDefaultAudience, Claims: &globalProvisionerClaims, @@ -742,18 +687,13 @@ func generateToken(sub, iss, aud, email string, sans []string, iat time.Time, jw return "", err } - id, err := randutil.ASCII(64) - if err != nil { - return "", err - } - claims := struct { jose.Claims Email string `json:"email"` SANS []string `json:"sans"` }{ Claims: jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: sub, Issuer: iss, IssuedAt: jose.NewNumericDate(iat), @@ -781,13 +721,9 @@ func generateCustomToken(sub, iss, aud string, jwk *jose.JSONWebKey, extraHeader return "", err } - id, err := randutil.ASCII(64) - if err != nil { - return "", err - } iat := time.Now() claims := jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: sub, Issuer: iss, IssuedAt: jose.NewNumericDate(iat), @@ -814,18 +750,13 @@ func generateOIDCToken(sub, iss, aud, email, preferredUsername string, iat time. return "", err } - id, err := randutil.ASCII(64) - if err != nil { - return "", err - } - claims := struct { jose.Claims Email string `json:"email"` PreferredUsername string `json:"preferred_username,omitempty"` }{ Claims: jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: sub, Issuer: iss, IssuedAt: jose.NewNumericDate(iat), @@ -914,17 +845,12 @@ func generateSSHToken(sub, iss, aud string, iat time.Time, sshOpts *SignSSHOptio return "", err } - id, err := randutil.ASCII(64) - if err != nil { - return "", err - } - claims := struct { jose.Claims Step *stepPayload `json:"step,omitempty"` }{ Claims: jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: sub, Issuer: iss, IssuedAt: jose.NewNumericDate(iat), diff --git a/authority/provisioner/x5c_test.go b/authority/provisioner/x5c_test.go index f394bc05b..db158cd9a 100644 --- a/authority/provisioner/x5c_test.go +++ b/authority/provisioner/x5c_test.go @@ -713,12 +713,10 @@ func TestX5C_AuthorizeSSHSign(t *testing.T) { p, err := generateX5C(nil) require.NoError(t, err) - id, err := randutil.ASCII(64) - require.NoError(t, err) now := time.Now() claims := &x5cPayload{ Claims: jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: "foo", Issuer: p.GetName(), IssuedAt: jose.NewNumericDate(now), @@ -741,12 +739,10 @@ func TestX5C_AuthorizeSSHSign(t *testing.T) { p, err := generateX5C(nil) require.NoError(t, err) - id, err := randutil.ASCII(64) - require.NoError(t, err) now := time.Now() claims := &x5cPayload{ Claims: jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: "foo", Issuer: p.GetName(), IssuedAt: jose.NewNumericDate(now), @@ -775,12 +771,10 @@ func TestX5C_AuthorizeSSHSign(t *testing.T) { p, err := generateX5C(nil) require.NoError(t, err) - id, err := randutil.ASCII(64) - require.NoError(t, err) now := time.Now() claims := &x5cPayload{ Claims: jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: "foo", Issuer: p.GetName(), IssuedAt: jose.NewNumericDate(now), @@ -803,12 +797,10 @@ func TestX5C_AuthorizeSSHSign(t *testing.T) { p, err := generateX5C(nil) require.NoError(t, err) - id, err := randutil.ASCII(64) - require.NoError(t, err) now := time.Now() claims := &x5cPayload{ Claims: jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: "foo", Issuer: p.GetName(), IssuedAt: jose.NewNumericDate(now), diff --git a/authority/ssh.go b/authority/ssh.go index 2608b9d43..a13c51051 100644 --- a/authority/ssh.go +++ b/authority/ssh.go @@ -574,11 +574,6 @@ func (a *Authority) SignSSHAddUser(ctx context.Context, key ssh.PublicKey, subje return nil, err } - nonce, err := randutil.ASCII(32) - if err != nil { - return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser") - } - var serial uint64 if err := binary.Read(rand.Reader, binary.BigEndian, &serial); err != nil { return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser: error reading random number") @@ -595,7 +590,7 @@ func (a *Authority) SignSSHAddUser(ctx context.Context, key ssh.PublicKey, subje addUserPrincipal := a.getAddUserPrincipal() cert := &ssh.Certificate{ - Nonce: []byte(nonce), + Nonce: []byte(randutil.ASCII(32)), Key: key, Serial: serial, CertType: ssh.UserCert, diff --git a/ca/adminClient.go b/ca/adminClient.go index 2ec4356f5..0f1f90c89 100644 --- a/ca/adminClient.go +++ b/ca/adminClient.go @@ -100,10 +100,7 @@ func NewAdminClient(endpoint string, opts ...ClientOption) (*AdminClient, error) func (c *AdminClient) generateAdminToken(aud *url.URL) (string, error) { // A random jwt id will be used to identify duplicated tokens - jwtID, err := randutil.Hex(64) // 256 bits - if err != nil { - return "", err - } + jwtID := randutil.Hex(64) // 256 bits // Drop any query string parameter from the token audience aud = &url.URL{ diff --git a/ca/bootstrap_test.go b/ca/bootstrap_test.go index da37eee58..851761acb 100644 --- a/ca/bootstrap_test.go +++ b/ca/bootstrap_test.go @@ -120,10 +120,6 @@ func generateBootstrapToken(ca, subject, sha string) string { if err != nil { panic(err) } - id, err := randutil.ASCII(64) - if err != nil { - panic(err) - } cl := struct { SHA string `json:"sha"` jose.Claims @@ -131,7 +127,7 @@ func generateBootstrapToken(ca, subject, sha string) string { }{ SHA: sha, Claims: jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: subject, Issuer: "mariano", NotBefore: jose.NewNumericDate(now), diff --git a/ca/ca_test.go b/ca/ca_test.go index 30a3fbbb7..facf2c477 100644 --- a/ca/ca_test.go +++ b/ca/ca_test.go @@ -175,8 +175,6 @@ ZEp7knvU2psWRw== } }, "fail commonname-claim": func(t *testing.T) *signTest { - jti, err := randutil.ASCII(32) - assert.FatalError(t, err) cl := struct { jose.Claims SANS []string `json:"sans"` @@ -187,7 +185,7 @@ ZEp7knvU2psWRw== NotBefore: jose.NewNumericDate(now), Expiry: jose.NewNumericDate(now.Add(time.Minute)), Audience: validAud, - ID: jti, + ID: randutil.ASCII(32), }, SANS: []string{"invalid"}, } @@ -208,8 +206,6 @@ ZEp7knvU2psWRw== } }, "ok": func(t *testing.T) *signTest { - jti, err := randutil.ASCII(32) - assert.FatalError(t, err) cl := struct { jose.Claims SANS []string `json:"sans"` @@ -220,7 +216,7 @@ ZEp7knvU2psWRw== NotBefore: jose.NewNumericDate(now), Expiry: jose.NewNumericDate(now.Add(time.Minute)), Audience: validAud, - ID: jti, + ID: randutil.ASCII(32), }, SANS: []string{"test.smallstep.com"}, } @@ -242,8 +238,6 @@ ZEp7knvU2psWRw== } }, "ok-backwards-compat-missing-subject-SAN": func(t *testing.T) *signTest { - jti, err := randutil.ASCII(32) - assert.FatalError(t, err) cl := struct { jose.Claims SANS []string `json:"sans"` @@ -254,7 +248,7 @@ ZEp7knvU2psWRw== NotBefore: jose.NewNumericDate(now), Expiry: jose.NewNumericDate(now.Add(time.Minute)), Audience: validAud, - ID: jti, + ID: randutil.ASCII(32), }, } raw, err := jose.Signed(sig).Claims(cl).CompactSerialize() diff --git a/ca/client.go b/ca/client.go index 7d0fd5176..1f29695bf 100644 --- a/ca/client.go +++ b/ca/client.go @@ -111,14 +111,7 @@ const requestIDHeader = "X-Request-Id" // newRequestID generates a new random UUIDv4 request ID. If it fails, // the request ID will be the empty string. -func newRequestID() string { - requestID, err := randutil.UUIDv4() - if err != nil { - return "" - } - - return requestID -} +func newRequestID() string { return randutil.UUIDv4() } // enforceRequestID checks if the X-Request-Id HTTP header is filled. If it's // empty, the context is searched for a request ID. If that's also empty, a new diff --git a/ca/provisioner.go b/ca/provisioner.go index 0de6733ce..5a934bfff 100644 --- a/ca/provisioner.go +++ b/ca/provisioner.go @@ -92,10 +92,7 @@ func (p *Provisioner) Token(subject string, sans ...string) (string, error) { } // A random jwt id will be used to identify duplicated tokens - jwtID, err := randutil.Hex(64) // 256 bits - if err != nil { - return "", err - } + jwtID := randutil.Hex(64) // 256 bits notBefore := time.Now() notAfter := notBefore.Add(tokenLifetime) @@ -122,15 +119,10 @@ func (p *Provisioner) Token(subject string, sans ...string) (string, error) { // SSHToken generates a SSH token. func (p *Provisioner) SSHToken(certType, keyID string, principals []string) (string, error) { - jwtID, err := randutil.Hex(64) - if err != nil { - return "", err - } - notBefore := time.Now() notAfter := notBefore.Add(tokenLifetime) tokOptions := []token.Options{ - token.WithJWTID(jwtID), + token.WithJWTID(randutil.Hex(64)), token.WithKid(p.kid), token.WithIssuer(p.name), token.WithAudience(p.sshAudience), diff --git a/ca/tls_test.go b/ca/tls_test.go index d1ce11ea7..c6e55c5fb 100644 --- a/ca/tls_test.go +++ b/ca/tls_test.go @@ -36,15 +36,12 @@ func generateOTT(t *testing.T, subject string) string { sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key}, opts) require.NoError(t, err) - id, err := randutil.ASCII(64) - require.NoError(t, err) - cl := struct { jose.Claims SANS []string `json:"sans"` }{ Claims: jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: subject, Issuer: "mariano", NotBefore: jose.NewNumericDate(now), diff --git a/cas/stepcas/jwk_issuer.go b/cas/stepcas/jwk_issuer.go index 2af4fceea..1d6abc63a 100644 --- a/cas/stepcas/jwk_issuer.go +++ b/cas/stepcas/jwk_issuer.go @@ -75,10 +75,7 @@ func (i *jwkIssuer) Lifetime(d time.Duration) time.Duration { } func (i *jwkIssuer) createToken(aud, sub string, sans []string, info *raInfo) (string, error) { - id, err := randutil.Hex(64) // 256 bits - if err != nil { - return "", err - } + id := randutil.Hex(64) // 256 bits claims := defaultClaims(i.issuer, sub, aud, id) builder := jose.Signed(i.signer).Claims(claims) diff --git a/cas/stepcas/stepcas_test.go b/cas/stepcas/stepcas_test.go index b4013792a..ba6ed39b5 100644 --- a/cas/stepcas/stepcas_test.go +++ b/cas/stepcas/stepcas_test.go @@ -281,10 +281,7 @@ func TestMain(m *testing.M) { } // Password used to encrypt the key. - testPassword, err = randutil.Hex(32) - if err != nil { - panic(err) - } + testPassword = randutil.Hex(32) // Encrypted JWK key used when the key is downloaded from the CA. jwe, err := jose.EncryptJWK(&jose.JSONWebKey{Key: testX5CKey}, []byte(testPassword)) diff --git a/cas/stepcas/x5c_issuer.go b/cas/stepcas/x5c_issuer.go index a005e5016..409a06710 100644 --- a/cas/stepcas/x5c_issuer.go +++ b/cas/stepcas/x5c_issuer.go @@ -82,11 +82,7 @@ func (i *x5cIssuer) createToken(aud, sub string, sans []string, info *raInfo) (s return "", err } - id, err := randutil.Hex(64) // 256 bits - if err != nil { - return "", err - } - + id := randutil.Hex(64) // 256 bits claims := defaultClaims(i.issuer, sub, aud, id) builder := jose.Signed(signer).Claims(claims) if len(sans) > 0 { diff --git a/commands/onboard.go b/commands/onboard.go index b3e95ac0f..cad33c678 100644 --- a/commands/onboard.go +++ b/commands/onboard.go @@ -113,10 +113,7 @@ func onboardAction(ctx *cli.Context) error { return errors.Wrap(err, "error unmarshaling response") } - password, err := randutil.ASCII(32) - if err != nil { - return err - } + password := randutil.ASCII(32) cfg.password = []byte(password) ui.Println("Initializing step-ca with the following configuration:") diff --git a/go.mod b/go.mod index ef92389ee..4911d1633 100644 --- a/go.mod +++ b/go.mod @@ -24,11 +24,10 @@ require ( github.com/newrelic/go-agent/v3 v3.39.0 github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.22.0 - github.com/rs/xid v1.6.0 github.com/sirupsen/logrus v1.9.3 github.com/slackhq/nebula v1.9.5 github.com/smallstep/assert v0.0.0-20200723003110-82e2b9b3b262 - github.com/smallstep/cli-utils v0.12.1 + github.com/smallstep/cli-utils v0.12.2-0.20250606021536-dd7f6cfa209e github.com/smallstep/go-attestation v0.4.4-0.20241119153605-2306d5b464ca github.com/smallstep/linkedca v0.23.0 github.com/smallstep/nosql v0.7.0 @@ -36,7 +35,7 @@ require ( github.com/smallstep/scep v0.0.0-20240926084937-8cf1ca453101 github.com/stretchr/testify v1.10.0 github.com/urfave/cli v1.22.16 - go.step.sm/crypto v0.66.0 + go.step.sm/crypto v0.66.1-0.20250605121706-9fa5daed8f0d go.uber.org/mock v0.5.2 golang.org/x/crypto v0.38.0 golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 diff --git a/go.sum b/go.sum index 529348406..ad1782ba8 100644 --- a/go.sum +++ b/go.sum @@ -333,8 +333,6 @@ github.com/redis/go-redis/v9 v9.8.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= -github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= -github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -353,8 +351,8 @@ github.com/slackhq/nebula v1.9.5 h1:ZrxcvP/lxwFglaijmiwXLuCSkybZMJnqSYI1S8DtGnY= github.com/slackhq/nebula v1.9.5/go.mod h1:1+4q4wd3dDAjO8rKCttSb9JIVbklQhuJiBp5I0lbIsQ= github.com/smallstep/assert v0.0.0-20200723003110-82e2b9b3b262 h1:unQFBIznI+VYD1/1fApl1A+9VcBk+9dcqGfnePY87LY= github.com/smallstep/assert v0.0.0-20200723003110-82e2b9b3b262/go.mod h1:MyOHs9Po2fbM1LHej6sBUT8ozbxmMOFG+E+rx/GSGuc= -github.com/smallstep/cli-utils v0.12.1 h1:D9QvfbFqiKq3snGZ2xDcXEFrdFJ1mQfPHZMq/leerpE= -github.com/smallstep/cli-utils v0.12.1/go.mod h1:skV2Neg8qjiKPu2fphM89H9bIxNpKiiRTnX9Q6Lc+20= +github.com/smallstep/cli-utils v0.12.2-0.20250606021536-dd7f6cfa209e h1:JKrEgsaEHFq8J7e10PpLpdpfNQO9I2Goeckz6JUDESA= +github.com/smallstep/cli-utils v0.12.2-0.20250606021536-dd7f6cfa209e/go.mod h1:viHftJUuCG0EiYXl/0YrWRW0cLupx+vJgxORcA7UDWg= github.com/smallstep/go-attestation v0.4.4-0.20241119153605-2306d5b464ca h1:VX8L0r8vybH0bPeaIxh4NQzafKQiqvlOn8pmOXbFLO4= github.com/smallstep/go-attestation v0.4.4-0.20241119153605-2306d5b464ca/go.mod h1:vNAduivU014fubg6ewygkAvQC0IQVXqdc8vaGl/0er4= github.com/smallstep/linkedca v0.23.0 h1:5W/7EudlK1HcCIdZM68dJlZ7orqCCCyv6bm2l/0JmLU= @@ -420,8 +418,8 @@ go.opentelemetry.io/otel/sdk/metric v1.35.0 h1:1RriWBmCKgkeHEhM7a2uMjMUfP7MsOF5J go.opentelemetry.io/otel/sdk/metric v1.35.0/go.mod h1:is6XYCUMpcKi+ZsOvfluY5YstFnhW0BidkR+gL+qN+w= go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs= go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc= -go.step.sm/crypto v0.66.0 h1:9TW6BEguOtcS9NIjja9bDQ+j8OjhenU/F6lJfHjbXNU= -go.step.sm/crypto v0.66.0/go.mod h1:anqGyvO/Px05D1mznHq4/a9wwP1I1DmMZvk+TWX5Dzo= +go.step.sm/crypto v0.66.1-0.20250605121706-9fa5daed8f0d h1:muLaBUsVoaFC6No3z1WHKuFYgtiVYFmCCmGaKCi+hgE= +go.step.sm/crypto v0.66.1-0.20250605121706-9fa5daed8f0d/go.mod h1:Em44XC7FzZ4DNK2gLM2wICyEKkaTkygSkpEdBQOGiGE= go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= diff --git a/middleware/requestid/requestid.go b/middleware/requestid/requestid.go index 886ac1478..896fdfaae 100644 --- a/middleware/requestid/requestid.go +++ b/middleware/requestid/requestid.go @@ -5,8 +5,6 @@ import ( "context" "net/http" - "github.com/rs/xid" - "go.step.sm/crypto/randutil" ) @@ -67,14 +65,7 @@ func (h *Handler) Middleware(next http.Handler) http.Handler { // newRequestID generates a new random UUIDv4 request ID. If UUIDv4 // generation fails, it'll fallback to generating a random ID using // github.com/rs/xid. -func newRequestID() string { - requestID, err := randutil.UUIDv4() - if err != nil { - requestID = xid.New().String() - } - - return requestID -} +func newRequestID() string { return randutil.UUIDv4() } type contextKey struct{} diff --git a/scep/authority_test.go b/scep/authority_test.go index cf092f002..22db1057c 100644 --- a/scep/authority_test.go +++ b/scep/authority_test.go @@ -24,13 +24,6 @@ import ( "go.step.sm/crypto/x509util" ) -func generateContent(t *testing.T, size int) []byte { - t.Helper() - b, err := randutil.Bytes(size) - require.NoError(t, err) - return b -} - func generateRecipients(t *testing.T) []*x509.Certificate { ca, err := minica.New() require.NoError(t, err) @@ -59,12 +52,12 @@ func TestAuthority_encrypt(t *testing.T) { args args wantErr bool }{ - {"alg-0", args{generateContent(t, 32), recipients, pkcs7.EncryptionAlgorithmDESCBC}, false}, - {"alg-1", args{generateContent(t, 32), recipients, pkcs7.EncryptionAlgorithmAES128CBC}, false}, - {"alg-2", args{generateContent(t, 32), recipients, pkcs7.EncryptionAlgorithmAES256CBC}, false}, - {"alg-3", args{generateContent(t, 32), recipients, pkcs7.EncryptionAlgorithmAES128GCM}, false}, - {"alg-4", args{generateContent(t, 32), recipients, pkcs7.EncryptionAlgorithmAES256GCM}, false}, - {"alg-unknown", args{generateContent(t, 32), recipients, 42}, true}, + {"alg-0", args{randutil.Bytes(32), recipients, pkcs7.EncryptionAlgorithmDESCBC}, false}, + {"alg-1", args{randutil.Bytes(32), recipients, pkcs7.EncryptionAlgorithmAES128CBC}, false}, + {"alg-2", args{randutil.Bytes(32), recipients, pkcs7.EncryptionAlgorithmAES256CBC}, false}, + {"alg-3", args{randutil.Bytes(32), recipients, pkcs7.EncryptionAlgorithmAES128GCM}, false}, + {"alg-4", args{randutil.Bytes(32), recipients, pkcs7.EncryptionAlgorithmAES256GCM}, false}, + {"alg-unknown", args{randutil.Bytes(32), recipients, 42}, true}, } for _, tt := range tests { tc := tt diff --git a/test/integration/requestid_test.go b/test/integration/requestid_test.go index 8801dc455..831490886 100644 --- a/test/integration/requestid_test.go +++ b/test/integration/requestid_test.go @@ -155,7 +155,7 @@ func Test_reflectRequestID(t *testing.T) { assert.NotEmpty(t, firstErr.RequestID) // TODO: include the below error in the JSON? It's currently only output to the CA logs. Also see https://github.com/smallstep/certificates/pull/759 - //assert.Equal(t, "/root/invalid was not found: certificate with fingerprint invalid was not found", apiErr.Msg) + // assert.Equal(t, "/root/invalid was not found: certificate with fingerprint invalid was not found", apiErr.Msg) } assert.Nil(t, rootResponse) @@ -230,15 +230,12 @@ func generateOTT(t *testing.T, jwk *jose.JSONWebKey, subject string) string { signer, err := jose.NewSigner(jose.SigningKey{Key: jwk.Key}, opts) require.NoError(t, err) - id, err := randutil.ASCII(64) - require.NoError(t, err) - cl := struct { jose.Claims SANS []string `json:"sans"` }{ Claims: jose.Claims{ - ID: id, + ID: randutil.ASCII(64), Subject: subject, Issuer: "jwk", NotBefore: jose.NewNumericDate(now),