From af6ef1b687be84f64e91679b37555b82bd044ad6 Mon Sep 17 00:00:00 2001 From: Jim Date: Thu, 5 Nov 2020 16:54:03 -0500 Subject: [PATCH] Refactor existing sentinel errors (#774) --- internal/auth/password/account.go | 4 +- internal/auth/password/argon2.go | 8 +- internal/auth/password/argon2_test.go | 8 +- internal/auth/password/authmethod.go | 4 +- internal/auth/password/repository.go | 7 +- internal/auth/password/repository_account.go | 52 ++--- .../auth/password/repository_account_test.go | 52 ++--- .../auth/password/repository_authmethod.go | 42 ++-- .../password/repository_authmethod_test.go | 22 +-- .../auth/password/repository_configuration.go | 11 +- .../password/repository_configuration_test.go | 12 +- internal/auth/password/repository_password.go | 39 ++-- .../auth/password/repository_password_test.go | 22 +-- internal/auth/password/repository_test.go | 10 +- internal/authtoken/repository.go | 34 ++-- internal/authtoken/repository_test.go | 18 +- internal/cmd/commands/database/init.go | 3 +- internal/db/error.go | 103 ---------- internal/db/error_test.go | 180 ------------------ internal/db/id.go | 3 +- internal/db/read_writer.go | 129 ++++++------- internal/db/read_writer_test.go | 135 +++++++------ internal/errors/error_test.go | 8 +- internal/host/static/host.go | 4 +- internal/host/static/host_catalog.go | 4 +- internal/host/static/host_set.go | 4 +- internal/host/static/host_set_member.go | 6 +- internal/host/static/repository.go | 7 +- internal/host/static/repository_host.go | 52 ++--- .../host/static/repository_host_catalog.go | 48 ++--- .../static/repository_host_catalog_test.go | 28 +-- internal/host/static/repository_host_set.go | 50 ++--- .../host/static/repository_host_set_member.go | 25 +-- .../static/repository_host_set_member_test.go | 24 +-- .../host/static/repository_host_set_test.go | 36 ++-- internal/host/static/repository_host_test.go | 36 ++-- internal/host/static/repository_test.go | 10 +- internal/iam/account.go | 3 +- internal/iam/group.go | 5 +- internal/iam/group_member.go | 9 +- internal/iam/group_member_test.go | 12 +- internal/iam/group_test.go | 12 +- internal/iam/ids.go | 3 +- internal/iam/ids_test.go | 6 +- internal/iam/principal_role.go | 17 +- internal/iam/principal_role_test.go | 22 +-- internal/iam/repository_group.go | 54 +++--- internal/iam/repository_group_test.go | 46 ++--- internal/iam/repository_principal_role.go | 23 +-- .../iam/repository_principal_role_test.go | 12 +- internal/iam/repository_role.go | 36 ++-- internal/iam/repository_role_grant.go | 23 +-- internal/iam/repository_role_grant_test.go | 8 +- internal/iam/repository_role_test.go | 38 ++-- internal/iam/repository_scope.go | 40 ++-- internal/iam/repository_scope_test.go | 4 +- internal/iam/repository_user.go | 79 ++++---- internal/iam/repository_user_test.go | 51 +++-- internal/iam/resource.go | 19 +- internal/iam/resource_test.go | 2 +- internal/iam/role.go | 7 +- internal/iam/role_grant.go | 7 +- internal/iam/role_grant_test.go | 6 +- internal/iam/role_test.go | 12 +- internal/iam/scope.go | 27 +-- internal/iam/scope_test.go | 4 +- internal/iam/user.go | 5 +- internal/iam/user_test.go | 2 +- internal/kms/database_key.go | 9 +- internal/kms/database_key_test.go | 6 +- internal/kms/database_key_version.go | 17 +- internal/kms/database_key_version_test.go | 10 +- internal/kms/kms.go | 10 +- internal/kms/oplog_key.go | 7 +- internal/kms/oplog_key_test.go | 6 +- internal/kms/oplog_key_version.go | 15 +- internal/kms/oplog_key_version_test.go | 10 +- internal/kms/repository.go | 17 +- internal/kms/repository_database_key.go | 15 +- internal/kms/repository_database_key_test.go | 26 +-- .../kms/repository_database_key_version.go | 31 +-- .../repository_database_key_version_test.go | 22 +-- internal/kms/repository_oplog_key.go | 15 +- internal/kms/repository_oplog_key_test.go | 26 +-- internal/kms/repository_oplog_key_version.go | 31 +-- .../kms/repository_oplog_key_version_test.go | 22 +-- internal/kms/repository_root_key.go | 15 +- internal/kms/repository_root_key_test.go | 20 +- internal/kms/repository_root_key_version.go | 27 +-- .../kms/repository_root_key_version_test.go | 22 +-- internal/kms/repository_session_key.go | 15 +- internal/kms/repository_session_key_test.go | 26 +-- .../kms/repository_session_key_version.go | 31 +-- .../repository_session_key_version_test.go | 22 +-- internal/kms/repository_test.go | 10 +- internal/kms/repository_token_key.go | 15 +- internal/kms/repository_token_key_test.go | 26 +-- internal/kms/repository_token_key_version.go | 31 +-- .../kms/repository_token_key_version_test.go | 22 +-- internal/kms/root_key.go | 9 +- internal/kms/root_key_test.go | 6 +- internal/kms/root_key_version.go | 13 +- internal/kms/root_key_version_test.go | 8 +- internal/kms/session_key.go | 7 +- internal/kms/session_key_test.go | 6 +- internal/kms/session_key_version.go | 15 +- internal/kms/session_key_version_test.go | 10 +- internal/kms/token_key.go | 7 +- internal/kms/token_key_test.go | 7 +- internal/kms/token_key_version.go | 15 +- internal/kms/token_key_version_test.go | 10 +- .../handlers/accounts/account_service.go | 11 +- .../authmethods/authmethod_service.go | 10 +- .../handlers/authtokens/authtoken_service.go | 7 +- .../servers/controller/handlers/errors.go | 9 +- .../controller/handlers/errors_test.go | 20 +- .../handlers/groups/group_service.go | 7 +- .../handlers/host_sets/host_set_service.go | 5 +- .../controller/handlers/hosts/host_service.go | 5 +- .../controller/handlers/roles/role_service.go | 7 +- .../handlers/sessions/session_service.go | 16 +- .../handlers/targets/target_service.go | 18 +- .../controller/handlers/users/user_service.go | 7 +- internal/session/connection.go | 23 +-- internal/session/connection_closed_reason.go | 4 +- internal/session/connection_closed_with.go | 6 +- internal/session/connection_state.go | 11 +- internal/session/connection_state_test.go | 8 +- internal/session/connection_test.go | 14 +- internal/session/repository_connection.go | 11 +- .../session/repository_connection_test.go | 6 +- internal/session/repository_session.go | 73 +++---- internal/session/repository_session_test.go | 49 ++--- internal/session/session.go | 63 +++--- internal/session/session_connect_with.go | 12 +- internal/session/session_test.go | 16 +- internal/session/state.go | 11 +- internal/session/state_test.go | 8 +- internal/session/term_reason.go | 4 +- internal/target/repository.go | 57 +++--- internal/target/repository_tcp_target.go | 27 +-- internal/target/repository_tcp_target_test.go | 30 +-- internal/target/repository_test.go | 14 +- internal/target/target_host_set.go | 9 +- internal/target/tcp_target.go | 9 +- internal/target/tcp_target_test.go | 8 +- 146 files changed, 1439 insertions(+), 1680 deletions(-) delete mode 100644 internal/db/error.go delete mode 100644 internal/db/error_test.go diff --git a/internal/auth/password/account.go b/internal/auth/password/account.go index 4fc8419b0..e25bcc18b 100644 --- a/internal/auth/password/account.go +++ b/internal/auth/password/account.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/auth/password/store" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/oplog" "google.golang.org/protobuf/proto" ) @@ -31,7 +31,7 @@ func NewAccount(authMethodId string, opt ...Option) (*Account, error) { // NOTE(mgaffney): The scopeId in the embedded *store.Account is // populated by a trigger in the database. if authMethodId == "" { - return nil, fmt.Errorf("new: password account: no auth method id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new: password account: no auth method id: %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) diff --git a/internal/auth/password/argon2.go b/internal/auth/password/argon2.go index 3ea038b22..210dd37ec 100644 --- a/internal/auth/password/argon2.go +++ b/internal/auth/password/argon2.go @@ -7,7 +7,7 @@ import ( "strings" "github.com/hashicorp/boundary/internal/auth/password/store" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/oplog" wrapping "github.com/hashicorp/go-kms-wrapping" "github.com/hashicorp/go-kms-wrapping/structwrapping" @@ -117,13 +117,13 @@ type Argon2Credential struct { func newArgon2Credential(accountId string, password string, conf *Argon2Configuration) (*Argon2Credential, error) { if accountId == "" { - return nil, fmt.Errorf("new: password argon2 credential: no accountId: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new: password argon2 credential: no accountId: %w", errors.ErrInvalidParameter) } if password == "" { - return nil, fmt.Errorf("new: password argon2 credential: no password: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new: password argon2 credential: no password: %w", errors.ErrInvalidParameter) } if conf == nil { - return nil, fmt.Errorf("new: password argon2 credential: no argon2 configuration: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new: password argon2 credential: no argon2 configuration: %w", errors.ErrInvalidParameter) } id, err := newArgon2CredentialId() diff --git a/internal/auth/password/argon2_test.go b/internal/auth/password/argon2_test.go index 56d6da568..e51a2debc 100644 --- a/internal/auth/password/argon2_test.go +++ b/internal/auth/password/argon2_test.go @@ -2,11 +2,11 @@ package password import ( "context" - "errors" "testing" "github.com/hashicorp/boundary/internal/auth/password/store" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/jinzhu/gorm" "github.com/stretchr/testify/assert" @@ -329,7 +329,7 @@ func TestArgon2Credential_New(t *testing.T) { conf: confs[0], }, want: nil, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "blank-password", @@ -339,7 +339,7 @@ func TestArgon2Credential_New(t *testing.T) { conf: confs[0], }, want: nil, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-configuration", @@ -349,7 +349,7 @@ func TestArgon2Credential_New(t *testing.T) { conf: nil, }, want: nil, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid-password", diff --git a/internal/auth/password/authmethod.go b/internal/auth/password/authmethod.go index 219664a5f..7293c1a3f 100644 --- a/internal/auth/password/authmethod.go +++ b/internal/auth/password/authmethod.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/auth/password/store" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/oplog" "google.golang.org/protobuf/proto" ) @@ -28,7 +28,7 @@ func allocAuthMethod() AuthMethod { // default values of 5 and 8 respectively. func NewAuthMethod(scopeId string, opt ...Option) (*AuthMethod, error) { if scopeId == "" { - return nil, fmt.Errorf("new: password auth method: no scope id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new: password auth method: no scope id: %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) diff --git a/internal/auth/password/repository.go b/internal/auth/password/repository.go index 8f02295cb..e5a3cbc15 100644 --- a/internal/auth/password/repository.go +++ b/internal/auth/password/repository.go @@ -5,6 +5,7 @@ import ( "strings" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" ) @@ -25,11 +26,11 @@ type Repository struct { func NewRepository(r db.Reader, w db.Writer, kms *kms.Kms, opt ...Option) (*Repository, error) { switch { case r == nil: - return nil, fmt.Errorf("db.Reader: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("db.Reader: %w", errors.ErrInvalidParameter) case w == nil: - return nil, fmt.Errorf("db.Writer: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("db.Writer: %w", errors.ErrInvalidParameter) case kms == nil: - return nil, fmt.Errorf("kms: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("kms: %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) diff --git a/internal/auth/password/repository_account.go b/internal/auth/password/repository_account.go index eecbf8510..71abcdffc 100644 --- a/internal/auth/password/repository_account.go +++ b/internal/auth/password/repository_account.go @@ -2,13 +2,13 @@ package password import ( "context" - "errors" "fmt" "regexp" "strings" "github.com/hashicorp/boundary/internal/db" dbcommon "github.com/hashicorp/boundary/internal/db/common" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" ) @@ -27,22 +27,22 @@ import ( // unique within a.AuthMethodId. func (r *Repository) CreateAccount(ctx context.Context, scopeId string, a *Account, opt ...Option) (*Account, error) { if a == nil { - return nil, fmt.Errorf("create: password account: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: password account: %w", errors.ErrInvalidParameter) } if a.Account == nil { - return nil, fmt.Errorf("create: password account: embedded Account: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: password account: embedded Account: %w", errors.ErrInvalidParameter) } if a.AuthMethodId == "" { - return nil, fmt.Errorf("create: password account: no auth method id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: password account: no auth method id: %w", errors.ErrInvalidParameter) } if a.PublicId != "" { - return nil, fmt.Errorf("create: password account: public id not empty: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: password account: public id not empty: %w", errors.ErrInvalidParameter) } if scopeId == "" { - return nil, fmt.Errorf("create: password account: scope id empty: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: password account: scope id empty: %w", errors.ErrInvalidParameter) } if !validLoginName(a.LoginName) { - return nil, fmt.Errorf("create: password account: invalid login name; must be all-lowercase alphanumeric: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: password account: invalid login name; must be all-lowercase alphanumeric: %w", errors.ErrInvalidParameter) } cc, err := r.currentConfig(ctx, a.AuthMethodId) @@ -105,9 +105,9 @@ func (r *Repository) CreateAccount(ctx context.Context, scopeId string, a *Accou ) if err != nil { - if db.IsUniqueError(err) { + if errors.IsUniqueError(err) { return nil, fmt.Errorf("create: password account: in auth method: %s: name %q or loginName %q already exists: %w", - a.AuthMethodId, a.Name, a.LoginName, db.ErrNotUnique) + a.AuthMethodId, a.Name, a.LoginName, errors.ErrNotUnique) } return nil, fmt.Errorf("create: password account: in auth method: %s: %w", a.AuthMethodId, err) } @@ -118,12 +118,12 @@ func (r *Repository) CreateAccount(ctx context.Context, scopeId string, a *Accou // found, it will return nil, nil. All options are ignored. func (r *Repository) LookupAccount(ctx context.Context, withPublicId string, opt ...Option) (*Account, error) { if withPublicId == "" { - return nil, fmt.Errorf("lookup: password account: missing public id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup: password account: missing public id %w", errors.ErrInvalidParameter) } a := allocAccount() a.PublicId = withPublicId if err := r.reader.LookupByPublicId(ctx, a); err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, nil } return nil, fmt.Errorf("lookup: password account: failed %w for %s", err, withPublicId) @@ -134,7 +134,7 @@ func (r *Repository) LookupAccount(ctx context.Context, withPublicId string, opt // ListAccounts in an auth method and supports WithLimit option. func (r *Repository) ListAccounts(ctx context.Context, withAuthMethodId string, opt ...Option) ([]*Account, error) { if withAuthMethodId == "" { - return nil, fmt.Errorf("list: password account: missing auth method id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list: password account: missing auth method id %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) limit := r.defaultLimit @@ -154,10 +154,10 @@ func (r *Repository) ListAccounts(ctx context.Context, withAuthMethodId string, // number of records deleted. All options are ignored. func (r *Repository) DeleteAccount(ctx context.Context, scopeId, withPublicId string, opt ...Option) (int, error) { if withPublicId == "" { - return db.NoRowsAffected, fmt.Errorf("delete: password account: missing public id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete: password account: missing public id: %w", errors.ErrInvalidParameter) } if scopeId == "" { - return db.NoRowsAffected, fmt.Errorf("delete: password account: scope id empty: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete: password account: scope id empty: %w", errors.ErrInvalidParameter) } ac := allocAccount() ac.PublicId = withPublicId @@ -177,7 +177,7 @@ func (r *Repository) DeleteAccount(ctx context.Context, scopeId, withPublicId st dAc := ac.clone() rowsDeleted, err = w.Delete(ctx, dAc, db.WithOplog(oplogWrapper, metadata)) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, @@ -214,19 +214,19 @@ func validLoginName(u string) bool { // cannot be set to NULL. func (r *Repository) UpdateAccount(ctx context.Context, scopeId string, a *Account, version uint32, fieldMaskPaths []string, opt ...Option) (*Account, int, error) { if a == nil { - return nil, db.NoRowsAffected, fmt.Errorf("update: password account: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: password account: %w", errors.ErrInvalidParameter) } if a.Account == nil { - return nil, db.NoRowsAffected, fmt.Errorf("update: password account: embedded Account: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: password account: embedded Account: %w", errors.ErrInvalidParameter) } if a.PublicId == "" { - return nil, db.NoRowsAffected, fmt.Errorf("update: password account: missing public id: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: password account: missing public id: %w", errors.ErrInvalidParameter) } if version == 0 { - return nil, db.NoRowsAffected, fmt.Errorf("update: password account: no version supplied: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: password account: no version supplied: %w", errors.ErrInvalidParameter) } if scopeId == "" { - return nil, db.NoRowsAffected, fmt.Errorf("update: password account: scope id empty: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: password account: scope id empty: %w", errors.ErrInvalidParameter) } var changeLoginName bool @@ -236,11 +236,11 @@ func (r *Repository) UpdateAccount(ctx context.Context, scopeId string, a *Accou case strings.EqualFold("Description", f): case strings.EqualFold("LoginName", f): if !validLoginName(a.LoginName) { - return nil, db.NoRowsAffected, fmt.Errorf("update: password account: invalid user name: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: password account: invalid user name: %w", errors.ErrInvalidParameter) } changeLoginName = true default: - return nil, db.NoRowsAffected, fmt.Errorf("update: password account: field: %s: %w", f, db.ErrInvalidFieldMask) + return nil, db.NoRowsAffected, fmt.Errorf("update: password account: field: %s: %w", f, errors.ErrInvalidFieldMask) } } var dbMask, nullFields []string @@ -254,7 +254,7 @@ func (r *Repository) UpdateAccount(ctx context.Context, scopeId string, a *Accou nil, ) if len(dbMask) == 0 && len(nullFields) == 0 { - return nil, db.NoRowsAffected, fmt.Errorf("update: password account: %w", db.ErrEmptyFieldMask) + return nil, db.NoRowsAffected, fmt.Errorf("update: password account: %w", errors.ErrEmptyFieldMask) } if changeLoginName { @@ -284,16 +284,16 @@ func (r *Repository) UpdateAccount(ctx context.Context, scopeId string, a *Accou var err error rowsUpdated, err = w.Update(ctx, returnedAccount, dbMask, nullFields, db.WithOplog(oplogWrapper, metadata), db.WithVersion(&version)) if err == nil && rowsUpdated > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, ) if err != nil { - if db.IsUniqueError(err) { + if errors.IsUniqueError(err) { return nil, db.NoRowsAffected, fmt.Errorf("update: password account: %s: name %s already exists: %w", - a.PublicId, a.Name, db.ErrNotUnique) + a.PublicId, a.Name, errors.ErrNotUnique) } return nil, db.NoRowsAffected, fmt.Errorf("update: password account: %s: %w", a.PublicId, err) } diff --git a/internal/auth/password/repository_account_test.go b/internal/auth/password/repository_account_test.go index 61bf65fc4..51ccec79c 100644 --- a/internal/auth/password/repository_account_test.go +++ b/internal/auth/password/repository_account_test.go @@ -2,13 +2,13 @@ package password import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/auth/password/store" "github.com/hashicorp/boundary/internal/db" dbassert "github.com/hashicorp/boundary/internal/db/assert" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -57,19 +57,19 @@ func TestRepository_CreateAccount(t *testing.T) { }{ { name: "nil-Account", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-embedded-Account", in: &Account{}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-no-scope-id", in: &Account{ Account: &store.Account{}, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-public-id-set", @@ -79,7 +79,7 @@ func TestRepository_CreateAccount(t *testing.T) { PublicId: "hcst_OOOOOOOOOO", }, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-loginname-uppercase", @@ -89,7 +89,7 @@ func TestRepository_CreateAccount(t *testing.T) { LoginName: "KaZmiErcZak11", }, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-loginname-leading-space", @@ -99,7 +99,7 @@ func TestRepository_CreateAccount(t *testing.T) { LoginName: " kazmierczak12", }, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-loginname-trailing-space", @@ -109,7 +109,7 @@ func TestRepository_CreateAccount(t *testing.T) { LoginName: "kazmierczak13 ", }, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-loginname-space-in-name", @@ -119,7 +119,7 @@ func TestRepository_CreateAccount(t *testing.T) { LoginName: "kazmier czak14", }, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-loginname-too-short", @@ -274,7 +274,7 @@ func TestRepository_CreateAccount(t *testing.T) { assert.Equal(got.CreateTime, got.UpdateTime) got2, err := repo.CreateAccount(context.Background(), org.GetPublicId(), in) - assert.Truef(errors.Is(err, db.ErrNotUnique), "want err: %v got: %v", db.ErrNotUnique, err) + assert.Truef(errors.Is(err, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err) assert.Nil(got2) }) @@ -339,7 +339,7 @@ func TestRepository_LookupAccount(t *testing.T) { }{ { name: "With no public id", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "With non existing account id", @@ -393,7 +393,7 @@ func TestRepository_DeleteAccount(t *testing.T) { }{ { name: "With no public id", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "With non existing account id", @@ -449,7 +449,7 @@ func TestRepository_ListAccounts(t *testing.T) { }{ { name: "With no auth method id", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "With no accounts id", @@ -633,7 +633,7 @@ func TestRepository_UpdateAccount(t *testing.T) { }, chgFn: makeNil(), masks: []string{"Name", "Description"}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-embedded-Account", @@ -642,7 +642,7 @@ func TestRepository_UpdateAccount(t *testing.T) { }, chgFn: makeEmbeddedNil(), masks: []string{"Name", "Description"}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "no-public-id", @@ -651,7 +651,7 @@ func TestRepository_UpdateAccount(t *testing.T) { }, chgFn: deletePublicId(), masks: []string{"Name", "Description"}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "updating-non-existent-Account", @@ -662,7 +662,7 @@ func TestRepository_UpdateAccount(t *testing.T) { }, chgFn: combine(nonExistentPublicId(), changeName("test-update-name-repo")), masks: []string{"Name"}, - wantIsErr: db.ErrRecordNotFound, + wantIsErr: errors.ErrRecordNotFound, }, { name: "empty-field-mask", @@ -672,7 +672,7 @@ func TestRepository_UpdateAccount(t *testing.T) { }, }, chgFn: changeName("test-update-name-repo"), - wantIsErr: db.ErrEmptyFieldMask, + wantIsErr: errors.ErrEmptyFieldMask, }, { name: "read-only-fields-in-field-mask", @@ -683,7 +683,7 @@ func TestRepository_UpdateAccount(t *testing.T) { }, chgFn: changeName("test-update-name-repo"), masks: []string{"PublicId", "CreateTime", "UpdateTime", "AuthMethodId"}, - wantIsErr: db.ErrInvalidFieldMask, + wantIsErr: errors.ErrInvalidFieldMask, }, { name: "unknown-field-in-field-mask", @@ -694,7 +694,7 @@ func TestRepository_UpdateAccount(t *testing.T) { }, chgFn: changeName("test-update-name-repo"), masks: []string{"Bilbo"}, - wantIsErr: db.ErrInvalidFieldMask, + wantIsErr: errors.ErrInvalidFieldMask, }, { name: "change-name", @@ -841,7 +841,7 @@ func TestRepository_UpdateAccount(t *testing.T) { }, chgFn: changeLoginName("KaZmIeRcZaK"), masks: []string{"LoginName"}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "change-login-name-to-short", @@ -863,7 +863,7 @@ func TestRepository_UpdateAccount(t *testing.T) { }, chgFn: changeLoginName(""), masks: []string{"LoginName"}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, } @@ -949,12 +949,12 @@ func TestRepository_UpdateAccount(t *testing.T) { ab.Name = name got2, gotCount2, err := repo.UpdateAccount(context.Background(), org.GetPublicId(), ab, 1, []string{"name"}) - assert.Truef(errors.Is(err, db.ErrNotUnique), "want err: %v got: %v", db.ErrNotUnique, err) + assert.Truef(errors.Is(err, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err) assert.Nil(got2) assert.Equal(db.NoRowsAffected, gotCount2, "row count") err = db.TestVerifyOplog(t, rw, ab.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) t.Run("valid-duplicate-names-diff-AuthMethods", func(t *testing.T) { @@ -1027,12 +1027,12 @@ func TestRepository_UpdateAccount(t *testing.T) { ab.LoginName = loginName got2, gotCount2, err := repo.UpdateAccount(context.Background(), org.GetPublicId(), ab, 1, []string{"LoginName"}) - assert.Truef(errors.Is(err, db.ErrNotUnique), "want err: %v got: %v", db.ErrNotUnique, err) + assert.Truef(errors.Is(err, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err) assert.Nil(got2) assert.Equal(db.NoRowsAffected, gotCount2, "row count") err = db.TestVerifyOplog(t, rw, ab.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) t.Run("valid-duplicate-loginnames-diff-AuthMethods", func(t *testing.T) { diff --git a/internal/auth/password/repository_authmethod.go b/internal/auth/password/repository_authmethod.go index 8be0608b6..2db1a12d1 100644 --- a/internal/auth/password/repository_authmethod.go +++ b/internal/auth/password/repository_authmethod.go @@ -2,12 +2,12 @@ package password import ( "context" - "errors" "fmt" "strings" "github.com/hashicorp/boundary/internal/db" dbcommon "github.com/hashicorp/boundary/internal/db/common" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" ) @@ -24,16 +24,16 @@ import ( // unique within m.ScopeId. func (r *Repository) CreateAuthMethod(ctx context.Context, m *AuthMethod, opt ...Option) (*AuthMethod, error) { if m == nil { - return nil, fmt.Errorf("create: password auth method: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: password auth method: %w", errors.ErrInvalidParameter) } if m.AuthMethod == nil { - return nil, fmt.Errorf("create: password auth method: embedded AuthMethod: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: password auth method: embedded AuthMethod: %w", errors.ErrInvalidParameter) } if m.ScopeId == "" { - return nil, fmt.Errorf("create: password auth method: no scope id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: password auth method: no scope id: %w", errors.ErrInvalidParameter) } if m.PublicId != "" { - return nil, fmt.Errorf("create: password auth method: public id not empty: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: password auth method: public id not empty: %w", errors.ErrInvalidParameter) } m = m.clone() @@ -41,7 +41,7 @@ func (r *Repository) CreateAuthMethod(ctx context.Context, m *AuthMethod, opt .. if opts.withPublicId != "" { if !strings.HasPrefix(opts.withPublicId, AuthMethodPrefix+"_") { - return nil, fmt.Errorf("create: password auth method: passed-in public ID %q has wrong prefix, should be %q: %w", opts.withPublicId, AuthMethodPrefix, db.ErrInvalidPublicId) + return nil, fmt.Errorf("create: password auth method: passed-in public ID %q has wrong prefix, should be %q: %w", opts.withPublicId, AuthMethodPrefix, errors.ErrInvalidPublicId) } m.PublicId = opts.withPublicId } else { @@ -86,9 +86,9 @@ func (r *Repository) CreateAuthMethod(ctx context.Context, m *AuthMethod, opt .. ) if err != nil { - if db.IsUniqueError(err) { + if errors.IsUniqueError(err) { return nil, fmt.Errorf("create: password auth method: in scope: %s: name %s already exists: %w", - m.ScopeId, m.Name, db.ErrNotUnique) + m.ScopeId, m.Name, errors.ErrNotUnique) } return nil, fmt.Errorf("create: password auth method: in scope: %s: %w", m.ScopeId, err) } @@ -99,12 +99,12 @@ func (r *Repository) CreateAuthMethod(ctx context.Context, m *AuthMethod, opt .. // found, it will return nil, nil. All options are ignored. func (r *Repository) LookupAuthMethod(ctx context.Context, publicId string, opt ...Option) (*AuthMethod, error) { if publicId == "" { - return nil, fmt.Errorf("lookup: password auth method: missing public id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup: password auth method: missing public id %w", errors.ErrInvalidParameter) } a := allocAuthMethod() a.PublicId = publicId if err := r.reader.LookupByPublicId(ctx, &a); err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, nil } return nil, fmt.Errorf("lookup: password auth method: failed %w for %s", err, publicId) @@ -115,7 +115,7 @@ func (r *Repository) LookupAuthMethod(ctx context.Context, publicId string, opt // ListAuthMethods returns a slice of AuthMethods for the scopeId. WithLimit is the only option supported. func (r *Repository) ListAuthMethods(ctx context.Context, scopeId string, opt ...Option) ([]*AuthMethod, error) { if scopeId == "" { - return nil, fmt.Errorf("list: password auth method: missing scope id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list: password auth method: missing scope id: %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) limit := r.defaultLimit @@ -135,7 +135,7 @@ func (r *Repository) ListAuthMethods(ctx context.Context, scopeId string, opt .. // number of records deleted. All options are ignored. func (r *Repository) DeleteAuthMethod(ctx context.Context, scopeId, publicId string, opt ...Option) (int, error) { if publicId == "" { - return db.NoRowsAffected, fmt.Errorf("delete: password auth method: missing public id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete: password auth method: missing public id: %w", errors.ErrInvalidParameter) } am := allocAuthMethod() am.PublicId = publicId @@ -155,7 +155,7 @@ func (r *Repository) DeleteAuthMethod(ctx context.Context, scopeId, publicId str dAc := am.clone() rowsDeleted, err = w.Delete(ctx, dAc, db.WithOplog(oplogWrapper, metadata)) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, @@ -182,13 +182,13 @@ func (r *Repository) DeleteAuthMethod(ctx context.Context, scopeId, publicId str // are included in the fieldMaskPaths, then an error is returned. func (r *Repository) UpdateAuthMethod(ctx context.Context, authMethod *AuthMethod, version uint32, fieldMaskPaths []string, opt ...Option) (*AuthMethod, int, error) { if authMethod == nil { - return nil, db.NoRowsAffected, fmt.Errorf("update: password auth method: missing authMethod: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: password auth method: missing authMethod: %w", errors.ErrInvalidParameter) } if authMethod.PublicId == "" { - return nil, db.NoRowsAffected, fmt.Errorf("update: password auth method: missing authMethod public id: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: password auth method: missing authMethod public id: %w", errors.ErrInvalidParameter) } if authMethod.ScopeId == "" { - return nil, db.NoRowsAffected, fmt.Errorf("update: password auth method: scope id empty: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: password auth method: scope id empty: %w", errors.ErrInvalidParameter) } for _, f := range fieldMaskPaths { switch { @@ -197,7 +197,7 @@ func (r *Repository) UpdateAuthMethod(ctx context.Context, authMethod *AuthMetho case strings.EqualFold("MinLoginNameLength", f): case strings.EqualFold("MinPasswordLength", f): default: - return nil, db.NoRowsAffected, fmt.Errorf("update: password auth method: field: %s: %w", f, db.ErrInvalidFieldMask) + return nil, db.NoRowsAffected, fmt.Errorf("update: password auth method: field: %s: %w", f, errors.ErrInvalidFieldMask) } } var dbMask, nullFields []string @@ -212,7 +212,7 @@ func (r *Repository) UpdateAuthMethod(ctx context.Context, authMethod *AuthMetho nil, ) if len(dbMask) == 0 && len(nullFields) == 0 { - return nil, db.NoRowsAffected, fmt.Errorf("update: password auth method: %w", db.ErrEmptyFieldMask) + return nil, db.NoRowsAffected, fmt.Errorf("update: password auth method: %w", errors.ErrEmptyFieldMask) } oplogWrapper, err := r.kms.GetWrapper(ctx, authMethod.ScopeId, kms.KeyPurposeOplog) @@ -240,14 +240,14 @@ func (r *Repository) UpdateAuthMethod(ctx context.Context, authMethod *AuthMetho dbOpts..., ) if err == nil && rowsUpdated > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, ) if err != nil { - if db.IsUniqueError(err) { - return nil, db.NoRowsAffected, fmt.Errorf("update: password auth method: authMethod %s already exists in scope %s: %w", authMethod.Name, authMethod.ScopeId, db.ErrNotUnique) + if errors.IsUniqueError(err) { + return nil, db.NoRowsAffected, fmt.Errorf("update: password auth method: authMethod %s already exists in scope %s: %w", authMethod.Name, authMethod.ScopeId, errors.ErrNotUnique) } return nil, db.NoRowsAffected, fmt.Errorf("update: password auth method: %w for %s", err, authMethod.PublicId) } diff --git a/internal/auth/password/repository_authmethod_test.go b/internal/auth/password/repository_authmethod_test.go index d1b4fb643..4448376af 100644 --- a/internal/auth/password/repository_authmethod_test.go +++ b/internal/auth/password/repository_authmethod_test.go @@ -2,7 +2,6 @@ package password import ( "context" - "errors" "strings" "testing" "time" @@ -11,6 +10,7 @@ import ( "github.com/hashicorp/boundary/internal/auth/password/store" "github.com/hashicorp/boundary/internal/db" dbassert "github.com/hashicorp/boundary/internal/db/assert" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -37,19 +37,19 @@ func TestRepository_CreateAuthMethod(t *testing.T) { }{ { name: "nil-AuthMethod", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-embedded-AuthMethod", in: &AuthMethod{}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-no-scope-id", in: &AuthMethod{ AuthMethod: &store.AuthMethod{}, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-public-id-set", @@ -59,7 +59,7 @@ func TestRepository_CreateAuthMethod(t *testing.T) { PublicId: "hcst_OOOOOOOOOO", }, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid-no-options", @@ -178,7 +178,7 @@ func TestRepository_CreateAuthMethod(t *testing.T) { assert.Equal(got.CreateTime, got.UpdateTime) got2, err := repo.CreateAuthMethod(context.Background(), in) - assert.Truef(errors.Is(err, db.ErrNotUnique), "want err: %v got: %v", db.ErrNotUnique, err) + assert.Truef(errors.Is(err, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err) assert.Nil(got2) }) @@ -251,7 +251,7 @@ func TestRepository_CreateAuthMethod(t *testing.T) { got, err := repo.CreateAuthMethod(context.Background(), &in, WithPublicId("invalid_idwithabadprefix")) assert.Error(err) assert.Nil(got) - assert.True(errors.Is(err, db.ErrInvalidPublicId)) + assert.True(errors.Is(err, errors.ErrInvalidPublicId)) }) } @@ -274,7 +274,7 @@ func TestRepository_LookupAuthMethod(t *testing.T) { }{ { name: "With no public id", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "With non existing auth method id", @@ -325,7 +325,7 @@ func TestRepository_DeleteAuthMethod(t *testing.T) { }{ { name: "With no public id", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "With non existing auth method id", @@ -377,7 +377,7 @@ func TestRepository_ListAuthMethods(t *testing.T) { }{ { name: "With no scope id", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "Scope with no auth methods", @@ -683,7 +683,7 @@ func TestRepository_UpdateAuthMethod(t *testing.T) { assert.Nil(updatedAM) err = db.TestVerifyOplog(t, rw, amToUpdate.GetPublicId(), db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) require.Error(err) - assert.Equal("record not found", err.Error()) + assert.Contains(err.Error(), "record not found") return } require.NoError(err) diff --git a/internal/auth/password/repository_configuration.go b/internal/auth/password/repository_configuration.go index 8d2bee16a..b2962acde 100644 --- a/internal/auth/password/repository_configuration.go +++ b/internal/auth/password/repository_configuration.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/boundary/internal/auth/password/store" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" ) @@ -21,7 +22,7 @@ type Configuration interface { // GetConfiguration returns the current configuration for authMethodId. func (r *Repository) GetConfiguration(ctx context.Context, authMethodId string) (Configuration, error) { if authMethodId == "" { - return nil, fmt.Errorf("get password configuration: no auth method id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("get password configuration: no auth method id: %w", errors.ErrInvalidParameter) } cc, err := r.currentConfig(ctx, authMethodId) if err != nil { @@ -42,10 +43,10 @@ func (r *Repository) GetConfiguration(ctx context.Context, authMethodId string) // updates AuthMethod to use the previous configuration. func (r *Repository) SetConfiguration(ctx context.Context, scopeId string, c Configuration) (Configuration, error) { if c == nil { - return nil, fmt.Errorf("set password configuration: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("set password configuration: %w", errors.ErrInvalidParameter) } if c.AuthMethodId() == "" { - return nil, fmt.Errorf("set password configuration: no auth method id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("set password configuration: no auth method id: %w", errors.ErrInvalidParameter) } if err := c.validate(); err != nil { return nil, fmt.Errorf("set password configuration: %w", err) @@ -89,7 +90,7 @@ func (r *Repository) setArgon2Conf(ctx context.Context, scopeId string, c *Argon func(rr db.Reader, w db.Writer) error { where, args := c.whereDup() if err := rr.LookupWhere(ctx, newArgon2Conf, where, args...); err != nil { - if err != db.ErrRecordNotFound { + if err != errors.ErrRecordNotFound { return err } newArgon2Conf = c.clone() @@ -101,7 +102,7 @@ func (r *Repository) setArgon2Conf(ctx context.Context, scopeId string, c *Argon a.PasswordConfId = newArgon2Conf.PrivateId rowsUpdated, err := w.Update(ctx, a, []string{"PasswordConfId"}, nil, db.WithOplog(oplogWrapper, a.oplog(oplog.OpType_OP_TYPE_UPDATE))) if err == nil && rowsUpdated > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, diff --git a/internal/auth/password/repository_configuration_test.go b/internal/auth/password/repository_configuration_test.go index 0f7b4f53f..b310f1a10 100644 --- a/internal/auth/password/repository_configuration_test.go +++ b/internal/auth/password/repository_configuration_test.go @@ -2,12 +2,12 @@ package password import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/auth/password/store" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -145,12 +145,12 @@ func TestRepository_GetConfiguration(t *testing.T) { { name: "invalid-no-authMethodId", authMethodId: "", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-authMethodId", authMethodId: "abcdefghijk", - wantIsErr: db.ErrRecordNotFound, + wantIsErr: errors.ErrRecordNotFound, }, { name: "valid-authMethodId", @@ -216,17 +216,17 @@ func TestRepository_SetConfiguration(t *testing.T) { }{ { name: "invalid-nil-config", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-embedded-config", in: &Argon2Configuration{}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-no-authMethodId", in: NewArgon2Configuration(), - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "unknown-configuration-type", diff --git a/internal/auth/password/repository_password.go b/internal/auth/password/repository_password.go index 6a0448ebc..582e7251c 100644 --- a/internal/auth/password/repository_password.go +++ b/internal/auth/password/repository_password.go @@ -3,10 +3,11 @@ package password import ( "context" "crypto/subtle" - "errors" "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" + "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" "golang.org/x/crypto/argon2" @@ -32,16 +33,16 @@ type authAccount struct { // the stored values are not using the current password settings. func (r *Repository) Authenticate(ctx context.Context, scopeId, authMethodId, loginName, password string) (*Account, error) { if authMethodId == "" { - return nil, fmt.Errorf("password authenticate: no authMethodId: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("password authenticate: no authMethodId: %w", errors.ErrInvalidParameter) } if loginName == "" { - return nil, fmt.Errorf("password authenticate: no loginName: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("password authenticate: no loginName: %w", errors.ErrInvalidParameter) } if password == "" { - return nil, fmt.Errorf("password authenticate: no password: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("password authenticate: no password: %w", errors.ErrInvalidParameter) } if scopeId == "" { - return nil, fmt.Errorf("password authenticate: no scopeId: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("password authenticate: no scopeId: %w", errors.ErrInvalidParameter) } databaseWrapper, err := r.kms.GetWrapper(ctx, scopeId, kms.KeyPurposeDatabase) @@ -85,7 +86,7 @@ func (r *Repository) Authenticate(ctx context.Context, scopeId, authMethodId, lo func(_ db.Reader, w db.Writer) error { rowsUpdated, err := w.Update(ctx, cred, fields, nil, db.WithOplog(oplogWrapper, metadata)) if err == nil && rowsUpdated > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, @@ -106,22 +107,22 @@ func (r *Repository) Authenticate(ctx context.Context, scopeId, authMethodId, lo // Returns nil, ErrPasswordsEqual if old and new are equal. func (r *Repository) ChangePassword(ctx context.Context, scopeId, accountId, old, new string, version uint32) (*Account, error) { if accountId == "" { - return nil, fmt.Errorf("change password: no account id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("change password: no account id: %w", errors.ErrInvalidParameter) } if old == "" { - return nil, fmt.Errorf("change password: no old password: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("change password: no old password: %w", errors.ErrInvalidParameter) } if new == "" { - return nil, fmt.Errorf("change password: no new password: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("change password: no new password: %w", errors.ErrInvalidParameter) } if old == new { return nil, fmt.Errorf("change password: %w", ErrPasswordsEqual) } if version == 0 { - return nil, fmt.Errorf("change password: no version supplied: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("change password: no version supplied: %w", errors.ErrInvalidParameter) } if scopeId == "" { - return nil, fmt.Errorf("change password: no scopeId: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("change password: no scopeId: %w", errors.ErrInvalidParameter) } authAccount, err := r.LookupAccount(ctx, accountId) @@ -129,7 +130,7 @@ func (r *Repository) ChangePassword(ctx context.Context, scopeId, accountId, old return nil, fmt.Errorf("change password: lookup account: %w", err) } if authAccount == nil { - return nil, fmt.Errorf("change password: lookup account: account not found: %w", db.ErrRecordNotFound) + return nil, fmt.Errorf("change password: lookup account: account not found: %w", errors.ErrRecordNotFound) } oplogWrapper, err := r.kms.GetWrapper(ctx, scopeId, kms.KeyPurposeOplog) @@ -183,7 +184,7 @@ func (r *Repository) ChangePassword(ctx context.Context, scopeId, accountId, old rowsDeleted, err := w.Delete(ctx, oldCred, db.WithOplog(oplogWrapper, oldCred.oplog(oplog.OpType_OP_TYPE_DELETE))) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } if err != nil { return err @@ -249,13 +250,13 @@ func (r *Repository) authenticate(ctx context.Context, scopeId, authMethodId, lo // contains an empty string, the password for accountId will be deleted. func (r *Repository) SetPassword(ctx context.Context, scopeId, accountId, password string, version uint32) (*Account, error) { if accountId == "" { - return nil, fmt.Errorf("set password: no accountId: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("set password: no accountId: %w", errors.ErrInvalidParameter) } if version == 0 { - return nil, fmt.Errorf("set password: no version supplied: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("set password: no version supplied: %w", errors.ErrInvalidParameter) } if scopeId == "" { - return nil, fmt.Errorf("set password: no scopeId: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("set password: no scopeId: %w", errors.ErrInvalidParameter) } oplogWrapper, err := r.kms.GetWrapper(ctx, scopeId, kms.KeyPurposeOplog) @@ -274,7 +275,7 @@ func (r *Repository) SetPassword(ctx context.Context, scopeId, accountId, passwo return nil, fmt.Errorf("set password: retrieve current configuration: %w", err) } if cc == nil { - return nil, fmt.Errorf("set password: retrieve current configuration: %w", db.ErrRecordNotFound) + return nil, fmt.Errorf("set password: retrieve current configuration: %w", errors.ErrRecordNotFound) } if cc.MinPasswordLength > len(password) { return nil, fmt.Errorf("set password: new password: %w", ErrTooShort) @@ -305,7 +306,7 @@ func (r *Repository) SetPassword(ctx context.Context, scopeId, accountId, passwo oldCred := allocCredential() if err := rr.LookupWhere(ctx, &oldCred, "password_account_id = ?", accountId); err != nil { - if !errors.Is(err, db.ErrRecordNotFound) { + if !errors.Is(err, errors.ErrRecordNotFound) { return err } } @@ -313,7 +314,7 @@ func (r *Repository) SetPassword(ctx context.Context, scopeId, accountId, passwo dCred := oldCred.clone() rowsDeleted, err := w.Delete(ctx, dCred, db.WithOplog(oplogWrapper, oldCred.oplog(oplog.OpType_OP_TYPE_DELETE))) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } if err != nil { return err diff --git a/internal/auth/password/repository_password_test.go b/internal/auth/password/repository_password_test.go index 5c713a1d7..af945f3fc 100644 --- a/internal/auth/password/repository_password_test.go +++ b/internal/auth/password/repository_password_test.go @@ -2,12 +2,12 @@ package password import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/auth/password/store" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -58,7 +58,7 @@ func TestRepository_Authenticate(t *testing.T) { loginName: inAcct.LoginName, password: passwd, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-no-loginName", @@ -67,7 +67,7 @@ func TestRepository_Authenticate(t *testing.T) { loginName: "", password: passwd, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-no-password", @@ -76,7 +76,7 @@ func TestRepository_Authenticate(t *testing.T) { loginName: inAcct.LoginName, password: "", }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid-authenticate", @@ -119,7 +119,7 @@ func TestRepository_Authenticate(t *testing.T) { assert.Equal(tt.args.loginName, authAcct.LoginName, "LoginName") err = db.TestVerifyOplog(t, rw, authAcct.CredentialId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } @@ -285,7 +285,7 @@ func TestRepository_ChangePassword(t *testing.T) { old: passwd, new: "12345678-changed", }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-no-current-password", @@ -294,7 +294,7 @@ func TestRepository_ChangePassword(t *testing.T) { old: "", new: "12345678-changed", }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-no-new-password", @@ -303,7 +303,7 @@ func TestRepository_ChangePassword(t *testing.T) { old: passwd, new: "", }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-same-passwords", @@ -322,7 +322,7 @@ func TestRepository_ChangePassword(t *testing.T) { new: "12345678-changed", }, wantAccount: false, - wantIsErr: db.ErrRecordNotFound, + wantIsErr: errors.ErrRecordNotFound, }, { name: "auth-failure-wrong-current-password", @@ -512,7 +512,7 @@ func TestRepository_SetPassword(t *testing.T) { name: "no id", pw: "anylongpassword", version: 1, - wantError: db.ErrInvalidParameter, + wantError: errors.ErrInvalidParameter, }, { name: "short pw", @@ -525,7 +525,7 @@ func TestRepository_SetPassword(t *testing.T) { name: "no version", accountId: badInputAcct.PublicId, pw: "anylongpassword", - wantError: db.ErrInvalidParameter, + wantError: errors.ErrInvalidParameter, }, } for _, tt := range badInputCases { diff --git a/internal/auth/password/repository_test.go b/internal/auth/password/repository_test.go index bf4482c34..011e518c5 100644 --- a/internal/auth/password/repository_test.go +++ b/internal/auth/password/repository_test.go @@ -1,10 +1,10 @@ package password import ( - "errors" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -67,7 +67,7 @@ func TestRepository_New(t *testing.T) { kms: kmsCache, }, want: nil, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-writer", @@ -77,7 +77,7 @@ func TestRepository_New(t *testing.T) { kms: kmsCache, }, want: nil, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-wrapper", @@ -87,7 +87,7 @@ func TestRepository_New(t *testing.T) { kms: nil, }, want: nil, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "all-nils", @@ -97,7 +97,7 @@ func TestRepository_New(t *testing.T) { kms: nil, }, want: nil, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, } for _, tt := range tests { diff --git a/internal/authtoken/repository.go b/internal/authtoken/repository.go index 8aed35a46..a88f451ee 100644 --- a/internal/authtoken/repository.go +++ b/internal/authtoken/repository.go @@ -2,7 +2,6 @@ package authtoken import ( "context" - "errors" "fmt" "time" @@ -10,6 +9,7 @@ import ( "github.com/hashicorp/boundary/internal/authtoken/store" "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/db/timestamp" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" ) @@ -37,11 +37,11 @@ type Repository struct { func NewRepository(r db.Reader, w db.Writer, kms *kms.Kms, opt ...Option) (*Repository, error) { switch { case r == nil: - return nil, fmt.Errorf("db.Reader: auth token: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("db.Reader: auth token: %w", errors.ErrInvalidParameter) case w == nil: - return nil, fmt.Errorf("db.Writer: auth token: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("db.Writer: auth token: %w", errors.ErrInvalidParameter) case kms == nil: - return nil, fmt.Errorf("kms: auth token: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("kms: auth token: %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) @@ -62,13 +62,13 @@ func NewRepository(r db.Reader, w db.Writer, kms *kms.Kms, opt ...Option) (*Repo // or an error will be returned. All options are ignored. func (r *Repository) CreateAuthToken(ctx context.Context, withIamUser *iam.User, withAuthAccountId string, opt ...Option) (*AuthToken, error) { if withIamUser == nil { - return nil, fmt.Errorf("create: auth token: no user: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: auth token: no user: %w", errors.ErrInvalidParameter) } if withIamUser.GetPublicId() == "" { - return nil, fmt.Errorf("create: auth token: no user id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: auth token: no user id: %w", errors.ErrInvalidParameter) } if withAuthAccountId == "" { - return nil, fmt.Errorf("create: auth token: no auth account id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: auth token: no auth account id: %w", errors.ErrInvalidParameter) } at := allocAuthToken() @@ -143,14 +143,14 @@ func (r *Repository) CreateAuthToken(ctx context.Context, withIamUser *iam.User, // All exported options are ignored. func (r *Repository) LookupAuthToken(ctx context.Context, id string, opt ...Option) (*AuthToken, error) { if id == "" { - return nil, fmt.Errorf("lookup: auth token: missing public id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup: auth token: missing public id: %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) at := allocAuthToken() at.PublicId = id if err := r.reader.LookupByPublicId(ctx, at); err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, nil } return nil, fmt.Errorf("auth token: lookup: %w", err) @@ -179,16 +179,16 @@ func (r *Repository) LookupAuthToken(ctx context.Context, id string, opt ...Opti // NOTE: Do not log or add the token string to any errors to avoid leaking it as it is a secret. func (r *Repository) ValidateToken(ctx context.Context, id, token string, opt ...Option) (*AuthToken, error) { if token == "" { - return nil, fmt.Errorf("validate token: auth token: missing token: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("validate token: auth token: missing token: %w", errors.ErrInvalidParameter) } if id == "" { - return nil, fmt.Errorf("validate token: auth token: missing public id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("validate token: auth token: missing public id: %w", errors.ErrInvalidParameter) } retAT, err := r.LookupAuthToken(ctx, id, withTokenValue()) if err != nil { retAT = nil - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, nil } return nil, fmt.Errorf("validate token: %w", err) @@ -258,7 +258,7 @@ func (r *Repository) ValidateToken(ctx context.Context, id, token string, opt .. []string{"ApproximateLastAccessTime"}, ) if err == nil && rowsUpdated > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, @@ -274,7 +274,7 @@ func (r *Repository) ValidateToken(ctx context.Context, id, token string, opt .. // ListAuthTokens in an org and supports the WithLimit option. func (r *Repository) ListAuthTokens(ctx context.Context, withOrgId string, opt ...Option) ([]*AuthToken, error) { if withOrgId == "" { - return nil, fmt.Errorf("list users: missing org id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list users: missing org id %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) limit := r.defaultLimit @@ -298,12 +298,12 @@ func (r *Repository) ListAuthTokens(ctx context.Context, withOrgId string, opt . // number of records deleted. All options are ignored. func (r *Repository) DeleteAuthToken(ctx context.Context, id string, opt ...Option) (int, error) { if id == "" { - return db.NoRowsAffected, fmt.Errorf("delete: auth token: missing public id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete: auth token: missing public id: %w", errors.ErrInvalidParameter) } at, err := r.LookupAuthToken(ctx, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return db.NoRowsAffected, nil } return db.NoRowsAffected, fmt.Errorf("delete: auth token: lookup %w", err) @@ -322,7 +322,7 @@ func (r *Repository) DeleteAuthToken(ctx context.Context, id string, opt ...Opti // tokens are not replicated, so they don't need oplog entries. rowsDeleted, err = w.Delete(ctx, deleteAT) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, diff --git a/internal/authtoken/repository_test.go b/internal/authtoken/repository_test.go index 017d6de3f..68a264f42 100644 --- a/internal/authtoken/repository_test.go +++ b/internal/authtoken/repository_test.go @@ -2,7 +2,6 @@ package authtoken import ( "context" - "errors" "sort" "testing" "time" @@ -18,6 +17,7 @@ import ( "github.com/hashicorp/boundary/internal/authtoken/store" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" ) @@ -77,7 +77,7 @@ func TestRepository_New(t *testing.T) { kms: kmsCache, }, want: nil, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-writer", @@ -87,7 +87,7 @@ func TestRepository_New(t *testing.T) { kms: kmsCache, }, want: nil, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-kms", @@ -97,7 +97,7 @@ func TestRepository_New(t *testing.T) { kms: nil, }, want: nil, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "all-nils", @@ -107,7 +107,7 @@ func TestRepository_New(t *testing.T) { kms: nil, }, want: nil, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -253,7 +253,7 @@ func TestRepository_LookupAuthToken(t *testing.T) { name: "bad-public-id", id: "", want: nil, - wantErr: db.ErrInvalidParameter, + wantErr: errors.ErrInvalidParameter, }, } @@ -347,7 +347,7 @@ func TestRepository_ValidateToken(t *testing.T) { id: at.GetPublicId(), token: "", want: nil, - wantErr: db.ErrInvalidParameter, + wantErr: errors.ErrInvalidParameter, }, { name: "mismatched-token", @@ -522,7 +522,7 @@ func TestRepository_DeleteAuthToken(t *testing.T) { name: "empty-public-id", id: "", want: 0, - wantErr: db.ErrInvalidParameter, + wantErr: errors.ErrInvalidParameter, }, } @@ -588,7 +588,7 @@ func TestRepository_ListAuthTokens(t *testing.T) { name: "empty-org-id", orgId: "", want: nil, - wantErr: db.ErrInvalidParameter, + wantErr: errors.ErrInvalidParameter, }, } diff --git a/internal/cmd/commands/database/init.go b/internal/cmd/commands/database/init.go index da193292d..0627ef697 100644 --- a/internal/cmd/commands/database/init.go +++ b/internal/cmd/commands/database/init.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/boundary/internal/cmd/base" "github.com/hashicorp/boundary/internal/cmd/config" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/types/scope" "github.com/hashicorp/boundary/sdk/wrapper" wrapping "github.com/hashicorp/go-kms-wrapping" @@ -254,7 +255,7 @@ func (c *InitCommand) Run(args []string) (retCode int) { c.UI.Info("Database already initialized.") return 0 } - case db.IsMissingTableError(err): + case errors.IsMissingTableError(err): // Doesn't exist so we continue on default: c.UI.Error(fmt.Errorf("Error querying database for init status: %w", err).Error()) diff --git a/internal/db/error.go b/internal/db/error.go deleted file mode 100644 index 90b645f36..000000000 --- a/internal/db/error.go +++ /dev/null @@ -1,103 +0,0 @@ -package db - -import ( - "errors" - - "github.com/lib/pq" -) - -// Errors returned from this package may be tested against these errors -// with errors.Is. -var ( - // ErrInvalidPublicId indicates an invalid PublicId. - ErrInvalidPublicId = errors.New("invalid publicId") - - // ErrInvalidParameter is returned by create and update methods if - // an attribute on a struct contains illegal or invalid values. - ErrInvalidParameter = errors.New("invalid parameter") - - // ErrInvalidFieldMask is returned by update methods if the field mask - // contains unknown fields or fields that cannot be updated. - ErrInvalidFieldMask = errors.New("invalid field mask") - - // ErrEmptyFieldMask is returned by update methods if the field mask is - // empty. - ErrEmptyFieldMask = errors.New("empty field mask") - - // ErrNotUnique is returned by create and update methods when a write - // to the repository resulted in a unique constraint violation. - ErrNotUnique = errors.New("unique constraint violation") - - // ErrRecordNotFound returns a "record not found" error and it only occurs - // when attempting to read from the database into struct. - // When reading into a slice it won't return this error. - ErrRecordNotFound = errors.New("record not found") - - // ErrMultipleRecords is returned by update and delete methods when a - // write to the repository would result in more than one record being - // changed resulting in the transaction being rolled back. - ErrMultipleRecords = errors.New("multiple records") -) - -// IsUniqueError returns a boolean indicating whether the error is known to -// report a unique constraint violation. -func IsUniqueError(err error) bool { - if err == nil { - return false - } - - var pqError *pq.Error - if errors.As(err, &pqError) { - if pqError.Code.Name() == "unique_violation" { - return true - } - } - - return false -} - -// IsCheckConstraintError returns a boolean indicating whether the error is -// known to report a check constraint violation. -func IsCheckConstraintError(err error) bool { - if err == nil { - return false - } - - var pqError *pq.Error - if errors.As(err, &pqError) { - if pqError.Code.Name() == "check_violation" { - return true - } - } - - return false -} - -// IsNotNullError returns a boolean indicating whether the error is known -// to report a not-null constraint violation. -func IsNotNullError(err error) bool { - if err == nil { - return false - } - - var pqError *pq.Error - if errors.As(err, &pqError) { - if pqError.Code.Name() == "not_null_violation" { - return true - } - } - - return false -} - -// IsMissingTableError returns a boolean indicating whether the error is known -// to report a undefined/missing table violation. -func IsMissingTableError(err error) bool { - var pqError *pq.Error - if errors.As(err, &pqError) { - if pqError.Code == "42P01" { - return true - } - } - return false -} diff --git a/internal/db/error_test.go b/internal/db/error_test.go deleted file mode 100644 index f68cd8f16..000000000 --- a/internal/db/error_test.go +++ /dev/null @@ -1,180 +0,0 @@ -package db - -import ( - "context" - "testing" - - "github.com/lib/pq" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestError_IsUnique(t *testing.T) { - var tests = []struct { - name string - in error - want bool - }{ - { - name: "nil-error", - in: nil, - want: false, - }, - { - name: "postgres-not-unique", - in: &pq.Error{ - Code: pq.ErrorCode("23503"), - }, - want: false, - }, - { - name: "postgres-is-unique2", - in: &pq.Error{ - Code: pq.ErrorCode("23505"), - }, - want: true, - }, - } - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - assert := assert.New(t) - err := tt.in - got := IsUniqueError(err) - assert.Equal(tt.want, got) - }) - } -} - -func TestError_IsCheckConstraint(t *testing.T) { - var tests = []struct { - name string - in error - want bool - }{ - { - name: "nil-error", - in: nil, - want: false, - }, - { - name: "postgres-not-check-constraint", - in: &pq.Error{ - Code: pq.ErrorCode("23505"), - }, - want: false, - }, - { - name: "postgres-is-check-constraint", - in: &pq.Error{ - Code: pq.ErrorCode("23514"), - }, - want: true, - }, - } - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - assert := assert.New(t) - err := tt.in - got := IsCheckConstraintError(err) - assert.Equal(tt.want, got) - }) - } -} - -func TestError_IsNotNullError(t *testing.T) { - var tests = []struct { - name string - in error - want bool - }{ - { - name: "nil-error", - in: nil, - want: false, - }, - { - name: "postgres-is-unique-not-not-null", - in: &pq.Error{ - Code: pq.ErrorCode("23505"), - }, - want: false, - }, - { - name: "postgres-is-check-constraint-not-not-null", - in: &pq.Error{ - Code: pq.ErrorCode("23514"), - }, - want: false, - }, - { - name: "postgres-is-not-null", - in: &pq.Error{ - Code: pq.ErrorCode("23502"), - }, - want: true, - }, - } - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - assert := assert.New(t) - err := tt.in - got := IsNotNullError(err) - assert.Equal(tt.want, got) - }) - } -} - -func TestError_IsMissingTableError(t *testing.T) { - var tests = []struct { - name string - in error - want bool - }{ - { - name: "nil-error", - in: nil, - want: false, - }, - { - name: "postgres-is-unique-not-not-null", - in: &pq.Error{ - Code: pq.ErrorCode("23505"), - }, - want: false, - }, - { - name: "postgres-is-check-constraint-not-not-null", - in: &pq.Error{ - Code: pq.ErrorCode("23514"), - }, - want: false, - }, - { - name: "postgres-is-missing-table", - in: &pq.Error{ - Code: pq.ErrorCode("42P01"), - }, - want: true, - }, - } - for _, tt := range tests { - tt := tt - t.Run(tt.name, func(t *testing.T) { - assert := assert.New(t) - err := tt.in - got := IsMissingTableError(err) - assert.Equal(tt.want, got) - }) - } - t.Run("query-missing-table", func(t *testing.T) { - assert, require := assert.New(t), require.New(t) - conn, _ := TestSetup(t, "postgres") - rw := New(conn) - _, err := rw.Query(context.Background(), "select * from non_existent_table", nil) - require.Error(err) - assert.True(IsMissingTableError(err)) - }) -} diff --git a/internal/db/id.go b/internal/db/id.go index aed8279a9..d506ffa6c 100644 --- a/internal/db/id.go +++ b/internal/db/id.go @@ -3,6 +3,7 @@ package db import ( "fmt" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/vault/sdk/helper/base62" ) @@ -17,7 +18,7 @@ func NewPublicId(prefix string) (string, error) { func newId(prefix string) (string, error) { if prefix == "" { - return "", fmt.Errorf("missing prefix %w", ErrInvalidParameter) + return "", fmt.Errorf("missing prefix %w", errors.ErrInvalidParameter) } publicId, err := base62.Random(10) if err != nil { diff --git a/internal/db/read_writer.go b/internal/db/read_writer.go index 8761be899..545eb00e6 100644 --- a/internal/db/read_writer.go +++ b/internal/db/read_writer.go @@ -3,13 +3,14 @@ package db import ( "context" "database/sql" - "errors" + stderrors "errors" "fmt" "reflect" "strings" "time" "github.com/hashicorp/boundary/internal/db/common" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/oplog" "github.com/hashicorp/boundary/internal/oplog/store" wrapping "github.com/hashicorp/go-kms-wrapping" @@ -181,7 +182,7 @@ func New(underlying *gorm.DB) *Db { // supported. func (rw *Db) Exec(ctx context.Context, sql string, values []interface{}, opt ...Option) (int, error) { if sql == "" { - return NoRowsAffected, fmt.Errorf("missing sql: %w", ErrInvalidParameter) + return NoRowsAffected, fmt.Errorf("missing sql: %w", errors.ErrInvalidParameter) } gormDb := rw.underlying.Exec(sql, values...) if gormDb.Error != nil { @@ -196,7 +197,7 @@ func (rw *Db) Exec(ctx context.Context, sql string, values []interface{}, opt .. // combination with ScanRows. func (rw *Db) Query(ctx context.Context, sql string, values []interface{}, opt ...Option) (*sql.Rows, error) { if sql == "" { - return nil, fmt.Errorf("raw missing sql: %w", ErrInvalidParameter) + return nil, fmt.Errorf("raw missing sql: %w", errors.ErrInvalidParameter) } gormDb := rw.underlying.Raw(sql, values...) if gormDb.Error != nil { @@ -208,10 +209,10 @@ func (rw *Db) Query(ctx context.Context, sql string, values []interface{}, opt . // Scan rows will scan the rows into the interface func (rw *Db) ScanRows(rows *sql.Rows, result interface{}) error { if rw.underlying == nil { - return fmt.Errorf("scan rows: missing underlying db %w", ErrInvalidParameter) + return fmt.Errorf("scan rows: missing underlying db %w", errors.ErrInvalidParameter) } if isNil(result) { - return fmt.Errorf("scan rows: result is missing %w", ErrInvalidParameter) + return fmt.Errorf("scan rows: result is missing %w", errors.ErrInvalidParameter) } return rw.underlying.ScanRows(rows, result) } @@ -235,15 +236,15 @@ func (rw *Db) lookupAfterWrite(ctx context.Context, i interface{}, opt ...Option // cannot be used together. WithLookup with to force a lookup after create. func (rw *Db) Create(ctx context.Context, i interface{}, opt ...Option) error { if rw.underlying == nil { - return fmt.Errorf("create: missing underlying db: %w", ErrInvalidParameter) + return fmt.Errorf("create: missing underlying db: %w", errors.ErrInvalidParameter) } if isNil(i) { - return fmt.Errorf("create: interface is missing: %w", ErrInvalidParameter) + return fmt.Errorf("create: interface is missing: %w", errors.ErrInvalidParameter) } opts := GetOpts(opt...) withOplog := opts.withOplog if withOplog && opts.newOplogMsg != nil { - return fmt.Errorf("create: both WithOplog and NewOplogMsg options have been specified: %w", ErrInvalidParameter) + return fmt.Errorf("create: both WithOplog and NewOplogMsg options have been specified: %w", errors.ErrInvalidParameter) } if withOplog { // let's validate oplog options before we start writing to the database @@ -297,20 +298,20 @@ func (rw *Db) Create(ctx context.Context, i interface{}, opt ...Option) error { // together. WithLookup is not a supported option. func (rw *Db) CreateItems(ctx context.Context, createItems []interface{}, opt ...Option) error { if rw.underlying == nil { - return fmt.Errorf("create items: missing underlying db: %w", ErrInvalidParameter) + return fmt.Errorf("create items: missing underlying db: %w", errors.ErrInvalidParameter) } if len(createItems) == 0 { - return fmt.Errorf("create items: no interfaces to create: %w", ErrInvalidParameter) + return fmt.Errorf("create items: no interfaces to create: %w", errors.ErrInvalidParameter) } opts := GetOpts(opt...) if opts.withLookup { - return fmt.Errorf("create items: with lookup not a supported option: %w", ErrInvalidParameter) + return fmt.Errorf("create items: with lookup not a supported option: %w", errors.ErrInvalidParameter) } if opts.newOplogMsg != nil { - return fmt.Errorf("create items: new oplog msg (singular) is not a supported option: %w", ErrInvalidParameter) + return fmt.Errorf("create items: new oplog msg (singular) is not a supported option: %w", errors.ErrInvalidParameter) } if opts.withOplog && opts.newOplogMsgs != nil { - return fmt.Errorf("create items: both WithOplog and NewOplogMsgs options have been specified: %w", ErrInvalidParameter) + return fmt.Errorf("create items: both WithOplog and NewOplogMsgs options have been specified: %w", errors.ErrInvalidParameter) } // verify that createItems are all the same type. var foundType reflect.Type @@ -320,7 +321,7 @@ func (rw *Db) CreateItems(ctx context.Context, createItems []interface{}, opt .. } currentType := reflect.TypeOf(v) if foundType != currentType { - return fmt.Errorf("create items: create items contains disparate types. item %d is not a %s: %w", i, foundType.Name(), ErrInvalidParameter) + return fmt.Errorf("create items: create items contains disparate types. item %d is not a %s: %w", i, foundType.Name(), errors.ErrInvalidParameter) } } var ticket *store.Ticket @@ -376,18 +377,18 @@ func (rw *Db) CreateItems(ctx context.Context, createItems []interface{}, opt .. // WithVersion option and will return an error. func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string, setToNullPaths []string, opt ...Option) (int, error) { if rw.underlying == nil { - return NoRowsAffected, fmt.Errorf("update: missing underlying db %w", ErrInvalidParameter) + return NoRowsAffected, fmt.Errorf("update: missing underlying db %w", errors.ErrInvalidParameter) } if isNil(i) { - return NoRowsAffected, fmt.Errorf("update: interface is missing %w", ErrInvalidParameter) + return NoRowsAffected, fmt.Errorf("update: interface is missing %w", errors.ErrInvalidParameter) } if len(fieldMaskPaths) == 0 && len(setToNullPaths) == 0 { - return NoRowsAffected, errors.New("update: both fieldMaskPaths and setToNullPaths are missing") + return NoRowsAffected, stderrors.New("update: both fieldMaskPaths and setToNullPaths are missing") } opts := GetOpts(opt...) withOplog := opts.withOplog if withOplog && opts.newOplogMsg != nil { - return NoRowsAffected, fmt.Errorf("update: both WithOplog and NewOplogMsg options have been specified: %w", ErrInvalidParameter) + return NoRowsAffected, fmt.Errorf("update: both WithOplog and NewOplogMsg options have been specified: %w", errors.ErrInvalidParameter) } // we need to filter out some non-updatable fields (like: CreateTime, etc) @@ -414,7 +415,7 @@ func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string for _, f := range scope.PrimaryFields() { if contains(fieldMaskPaths, f.Name) { - return NoRowsAffected, fmt.Errorf("update: not allowed on primary key field %s: %w", f.Name, ErrInvalidFieldMask) + return NoRowsAffected, fmt.Errorf("update: not allowed on primary key field %s: %w", f.Name, errors.ErrInvalidFieldMask) } } @@ -447,7 +448,7 @@ func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string var args []interface{} if opts.WithVersion != nil { if *opts.WithVersion == 0 { - return NoRowsAffected, fmt.Errorf("update: with version option is zero: %w", ErrInvalidParameter) + return NoRowsAffected, fmt.Errorf("update: with version option is zero: %w", errors.ErrInvalidParameter) } if _, ok := scope.FieldByName("version"); !ok { return NoRowsAffected, fmt.Errorf("update: %s does not have a version field", scope.TableName()) @@ -463,7 +464,7 @@ func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string } if underlying.Error != nil { if err == gorm.ErrRecordNotFound { - return NoRowsAffected, fmt.Errorf("update: failed: %w", ErrRecordNotFound) + return NoRowsAffected, fmt.Errorf("update: failed: %w", errors.ErrRecordNotFound) } return NoRowsAffected, fmt.Errorf("update: failed: %w", underlying.Error) } @@ -510,15 +511,15 @@ func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string // deleted and any errors. func (rw *Db) Delete(ctx context.Context, i interface{}, opt ...Option) (int, error) { if rw.underlying == nil { - return NoRowsAffected, fmt.Errorf("delete: missing underlying db %w", ErrInvalidParameter) + return NoRowsAffected, fmt.Errorf("delete: missing underlying db %w", errors.ErrInvalidParameter) } if isNil(i) { - return NoRowsAffected, fmt.Errorf("delete: interface is missing %w", ErrInvalidParameter) + return NoRowsAffected, fmt.Errorf("delete: interface is missing %w", errors.ErrInvalidParameter) } opts := GetOpts(opt...) withOplog := opts.withOplog if withOplog && opts.newOplogMsg != nil { - return NoRowsAffected, fmt.Errorf("delete: both WithOplog and NewOplogMsg options have been specified: %w", ErrInvalidParameter) + return NoRowsAffected, fmt.Errorf("delete: both WithOplog and NewOplogMsg options have been specified: %w", errors.ErrInvalidParameter) } // This is not a boundary scope, but rather a gorm Scope: // https://godoc.org/github.com/jinzhu/gorm#DB.NewScope @@ -573,17 +574,17 @@ func (rw *Db) Delete(ctx context.Context, i interface{}, opt ...Option) (int, er // together. func (rw *Db) DeleteItems(ctx context.Context, deleteItems []interface{}, opt ...Option) (int, error) { if rw.underlying == nil { - return NoRowsAffected, fmt.Errorf("delete items: missing underlying db: %w", ErrInvalidParameter) + return NoRowsAffected, fmt.Errorf("delete items: missing underlying db: %w", errors.ErrInvalidParameter) } if len(deleteItems) == 0 { - return NoRowsAffected, fmt.Errorf("delete items: no interfaces to delete: %w", ErrInvalidParameter) + return NoRowsAffected, fmt.Errorf("delete items: no interfaces to delete: %w", errors.ErrInvalidParameter) } opts := GetOpts(opt...) if opts.newOplogMsg != nil { - return NoRowsAffected, fmt.Errorf("delete items: new oplog msg (singular) is not a supported option: %w", ErrInvalidParameter) + return NoRowsAffected, fmt.Errorf("delete items: new oplog msg (singular) is not a supported option: %w", errors.ErrInvalidParameter) } if opts.withOplog && opts.newOplogMsgs != nil { - return NoRowsAffected, fmt.Errorf("delete items: both WithOplog and NewOplogMsgs options have been specified: %w", ErrInvalidParameter) + return NoRowsAffected, fmt.Errorf("delete items: both WithOplog and NewOplogMsgs options have been specified: %w", errors.ErrInvalidParameter) } // verify that createItems are all the same type. var foundType reflect.Type @@ -593,7 +594,7 @@ func (rw *Db) DeleteItems(ctx context.Context, deleteItems []interface{}, opt .. } currentType := reflect.TypeOf(v) if foundType != currentType { - return NoRowsAffected, fmt.Errorf("delete items: items contain disparate types. item %d is not a %s: %w", i, foundType.Name(), ErrInvalidParameter) + return NoRowsAffected, fmt.Errorf("delete items: items contain disparate types. item %d is not a %s: %w", i, foundType.Name(), errors.ErrInvalidParameter) } } @@ -639,21 +640,21 @@ func (rw *Db) DeleteItems(ctx context.Context, deleteItems []interface{}, opt .. func validateOplogArgs(i interface{}, opts Options) (oplog.ReplayableMessage, error) { oplogArgs := opts.oplogOpts if oplogArgs.wrapper == nil { - return nil, fmt.Errorf("error no wrapper WithOplog: %w", ErrInvalidParameter) + return nil, fmt.Errorf("error no wrapper WithOplog: %w", errors.ErrInvalidParameter) } if len(oplogArgs.metadata) == 0 { - return nil, fmt.Errorf("error no metadata for WithOplog: %w", ErrInvalidParameter) + return nil, fmt.Errorf("error no metadata for WithOplog: %w", errors.ErrInvalidParameter) } replayable, ok := i.(oplog.ReplayableMessage) if !ok { - return nil, errors.New("error not a replayable message for WithOplog") + return nil, stderrors.New("error not a replayable message for WithOplog") } return replayable, nil } func (rw *Db) getTicketFor(aggregateName string) (*store.Ticket, error) { if rw.underlying == nil { - return nil, fmt.Errorf("get ticket for %s: underlying db missing: %w", aggregateName, ErrInvalidParameter) + return nil, fmt.Errorf("get ticket for %s: underlying db missing: %w", aggregateName, errors.ErrInvalidParameter) } ticketer, err := oplog.NewGormTicketer(rw.underlying, oplog.WithAggregateNames(true)) if err != nil { @@ -670,21 +671,21 @@ func (rw *Db) getTicketFor(aggregateName string) (*store.Ticket, error) { // be used to WriteOplogEntryWith for that aggregate root. func (rw *Db) GetTicket(i interface{}) (*store.Ticket, error) { if rw.underlying == nil { - return nil, fmt.Errorf("get ticket: underlying db missing: %w", ErrInvalidParameter) + return nil, fmt.Errorf("get ticket: underlying db missing: %w", errors.ErrInvalidParameter) } if isNil(i) { - return nil, fmt.Errorf("get ticket: interface is missing %w", ErrInvalidParameter) + return nil, fmt.Errorf("get ticket: interface is missing %w", errors.ErrInvalidParameter) } replayable, ok := i.(oplog.ReplayableMessage) if !ok { - return nil, fmt.Errorf("get ticket: not a replayable message %w", ErrInvalidParameter) + return nil, fmt.Errorf("get ticket: not a replayable message %w", errors.ErrInvalidParameter) } return rw.getTicketFor(replayable.TableName()) } func (rw *Db) oplogMsgsForItems(ctx context.Context, opType OpType, opts Options, items []interface{}) ([]*oplog.Message, error) { if len(items) == 0 { - return nil, fmt.Errorf("oplog msgs for items: items is empty: %w", ErrInvalidParameter) + return nil, fmt.Errorf("oplog msgs for items: items is empty: %w", errors.ErrInvalidParameter) } oplogMsgs := []*oplog.Message{} var foundType reflect.Type @@ -694,7 +695,7 @@ func (rw *Db) oplogMsgsForItems(ctx context.Context, opType OpType, opts Options } currentType := reflect.TypeOf(item) if foundType != currentType { - return nil, fmt.Errorf("oplog msgs for items: items contains disparate types. item (%d) %s is not a %s: %w", i, currentType, foundType, ErrInvalidParameter) + return nil, fmt.Errorf("oplog msgs for items: items contains disparate types. item (%d) %s is not a %s: %w", i, currentType, foundType, errors.ErrInvalidParameter) } msg, err := rw.newOplogMessage(ctx, opType, item, WithFieldMaskPaths(opts.WithFieldMaskPaths), WithNullPaths(opts.WithNullPaths)) if err != nil { @@ -711,19 +712,19 @@ func (rw *Db) oplogMsgsForItems(ctx context.Context, opType OpType, opts Options func (rw *Db) addOplogForItems(ctx context.Context, opType OpType, opts Options, ticket *store.Ticket, items []interface{}) error { oplogArgs := opts.oplogOpts if ticket == nil { - return fmt.Errorf("oplog for items: ticket is missing: %w", ErrInvalidParameter) + return fmt.Errorf("oplog for items: ticket is missing: %w", errors.ErrInvalidParameter) } if items == nil { - return fmt.Errorf("oplog for items: items are missing: %w", ErrInvalidParameter) + return fmt.Errorf("oplog for items: items are missing: %w", errors.ErrInvalidParameter) } if len(items) == 0 { - return fmt.Errorf("oplog for items: items is empty: %w", ErrInvalidParameter) + return fmt.Errorf("oplog for items: items is empty: %w", errors.ErrInvalidParameter) } if oplogArgs.metadata == nil { - return fmt.Errorf("oplog for items: metadata is missing: %w", ErrInvalidParameter) + return fmt.Errorf("oplog for items: metadata is missing: %w", errors.ErrInvalidParameter) } if oplogArgs.wrapper == nil { - return fmt.Errorf("oplog for items: wrapper is missing: %w", ErrInvalidParameter) + return fmt.Errorf("oplog for items: wrapper is missing: %w", errors.ErrInvalidParameter) } oplogMsgs, err := rw.oplogMsgsForItems(ctx, opType, opts, items) @@ -766,7 +767,7 @@ func (rw *Db) addOplog(ctx context.Context, opType OpType, opts Options, ticket return err } if ticket == nil { - return fmt.Errorf("add oplog: missing ticket %w", ErrInvalidParameter) + return fmt.Errorf("add oplog: missing ticket %w", errors.ErrInvalidParameter) } ticketer, err := oplog.NewGormTicketer(rw.underlying, oplog.WithAggregateNames(true)) if err != nil { @@ -801,22 +802,22 @@ func (rw *Db) addOplog(ctx context.Context, opType OpType, opts Options, ticket // the ticket's aggregateName. No options are currently supported. func (rw *Db) WriteOplogEntryWith(ctx context.Context, wrapper wrapping.Wrapper, ticket *store.Ticket, metadata oplog.Metadata, msgs []*oplog.Message, opt ...Option) error { if wrapper == nil { - return fmt.Errorf("write oplog: wrapper is unset %w", ErrInvalidParameter) + return fmt.Errorf("write oplog: wrapper is unset %w", errors.ErrInvalidParameter) } if ticket == nil { - return fmt.Errorf("write oplog: ticket is unset %w", ErrInvalidParameter) + return fmt.Errorf("write oplog: ticket is unset %w", errors.ErrInvalidParameter) } if len(msgs) == 0 { - return fmt.Errorf("write oplog: msgs are empty %w", ErrInvalidParameter) + return fmt.Errorf("write oplog: msgs are empty %w", errors.ErrInvalidParameter) } if rw.underlying == nil { - return fmt.Errorf("write oplog: underlying is unset %w", ErrInvalidParameter) + return fmt.Errorf("write oplog: underlying is unset %w", errors.ErrInvalidParameter) } if metadata == nil { - return fmt.Errorf("write oplog: metadata is unset %w", ErrInvalidParameter) + return fmt.Errorf("write oplog: metadata is unset %w", errors.ErrInvalidParameter) } if len(metadata) == 0 { - return fmt.Errorf("write oplog: metadata is empty %w", ErrInvalidParameter) + return fmt.Errorf("write oplog: metadata is empty %w", errors.ErrInvalidParameter) } ticketer, err := oplog.NewGormTicketer(rw.underlying, oplog.WithAggregateNames(true)) @@ -849,7 +850,7 @@ func (rw *Db) newOplogMessage(ctx context.Context, opType OpType, i interface{}, opts := GetOpts(opt...) replayable, ok := i.(oplog.ReplayableMessage) if !ok { - return nil, errors.New("error not a replayable interface") + return nil, stderrors.New("error not a replayable interface") } msg := oplog.Message{ Message: i.(proto.Message), @@ -876,7 +877,7 @@ func (rw *Db) newOplogMessage(ctx context.Context, opType OpType, i interface{}, // be reset before retry func (w *Db) DoTx(ctx context.Context, retries uint, backOff Backoff, Handler TxHandler) (RetryInfo, error) { if w.underlying == nil { - return RetryInfo{}, errors.New("do underlying db is nil") + return RetryInfo{}, stderrors.New("do underlying db is nil") } info := RetryInfo{} for attempts := uint(1); ; attempts++ { @@ -916,10 +917,10 @@ func (w *Db) DoTx(ctx context.Context, retries uint, backOff Backoff, Handler Tx // must be unique. Options are ignored. func (rw *Db) LookupById(ctx context.Context, resourceWithIder interface{}, opt ...Option) error { if rw.underlying == nil { - return fmt.Errorf("lookup by id: underlying db nil %w", ErrInvalidParameter) + return fmt.Errorf("lookup by id: underlying db nil %w", errors.ErrInvalidParameter) } if reflect.ValueOf(resourceWithIder).Kind() != reflect.Ptr { - return fmt.Errorf("lookup by id: interface parameter must to be a pointer: %w", ErrInvalidParameter) + return fmt.Errorf("lookup by id: interface parameter must to be a pointer: %w", errors.ErrInvalidParameter) } primaryKey, where, err := primaryKeyWhere(resourceWithIder) if err != nil { @@ -927,7 +928,7 @@ func (rw *Db) LookupById(ctx context.Context, resourceWithIder interface{}, opt } if err := rw.underlying.Where(where, primaryKey).First(resourceWithIder).Error; err != nil { if err == gorm.ErrRecordNotFound { - return ErrRecordNotFound + return errors.ErrRecordNotFound } return err } @@ -944,10 +945,10 @@ func primaryKeyWhere(resourceWithIder interface{}) (pkey string, w string, e err primaryKey = resourceType.GetPrivateId() where = "private_id = ?" default: - return "", "", fmt.Errorf("unsupported interface type %w", ErrInvalidParameter) + return "", "", fmt.Errorf("unsupported interface type %w", errors.ErrInvalidParameter) } if primaryKey == "" { - return "", "", fmt.Errorf("primary key unset %w", ErrInvalidParameter) + return "", "", fmt.Errorf("primary key unset %w", errors.ErrInvalidParameter) } return primaryKey, where, nil } @@ -961,14 +962,14 @@ func (rw *Db) LookupByPublicId(ctx context.Context, resource ResourcePublicIder, // LookupWhere will lookup the first resource using a where clause with parameters (it only returns the first one) func (rw *Db) LookupWhere(ctx context.Context, resource interface{}, where string, args ...interface{}) error { if rw.underlying == nil { - return errors.New("error underlying db nil for lookup by") + return stderrors.New("error underlying db nil for lookup by") } if reflect.ValueOf(resource).Kind() != reflect.Ptr { - return errors.New("error interface parameter must to be a pointer for lookup by") + return stderrors.New("error interface parameter must to be a pointer for lookup by") } if err := rw.underlying.Where(where, args...).First(resource).Error; err != nil { if err == gorm.ErrRecordNotFound { - return ErrRecordNotFound + return errors.ErrRecordNotFound } return err } @@ -982,10 +983,10 @@ func (rw *Db) LookupWhere(ctx context.Context, resource interface{}, where strin func (rw *Db) SearchWhere(ctx context.Context, resources interface{}, where string, args []interface{}, opt ...Option) error { opts := GetOpts(opt...) if rw.underlying == nil { - return errors.New("error underlying db nil for search by") + return stderrors.New("error underlying db nil for search by") } if reflect.ValueOf(resources).Kind() != reflect.Ptr { - return errors.New("error interface parameter must to be a pointer for search by") + return stderrors.New("error interface parameter must to be a pointer for search by") } var err error db := rw.underlying.Order(opts.withOrder) @@ -1081,10 +1082,10 @@ func Clear(i interface{}, fields []string, depth int) error { switch v.Kind() { default: - return ErrInvalidParameter + return errors.ErrInvalidParameter case reflect.Ptr: if v.IsNil() || v.Elem().Kind() != reflect.Struct { - return ErrInvalidParameter + return errors.ErrInvalidParameter } clear(v, fm, depth) } diff --git a/internal/db/read_writer_test.go b/internal/db/read_writer_test.go index 24e1ee5d8..a3e9d4be9 100644 --- a/internal/db/read_writer_test.go +++ b/internal/db/read_writer_test.go @@ -2,7 +2,7 @@ package db import ( "context" - "errors" + stderrors "errors" "fmt" "io" "strconv" @@ -13,6 +13,7 @@ import ( "github.com/golang/protobuf/ptypes" "github.com/hashicorp/boundary/internal/db/db_test" "github.com/hashicorp/boundary/internal/db/timestamp" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/oplog" "github.com/hashicorp/boundary/internal/oplog/store" wrapping "github.com/hashicorp/go-kms-wrapping" @@ -128,7 +129,7 @@ func TestDb_Update(t *testing.T) { }, want: 0, wantErr: true, - wantErrMsg: "update: with version option is zero: invalid parameter", + wantErrMsg: "update: with version option is zero: invalid parameter:", }, { name: "simple-with-version", @@ -275,7 +276,7 @@ func TestDb_Update(t *testing.T) { }, want: 0, wantErr: true, - wantErrMsg: "update: not allowed on primary key field Id: invalid field mask", + wantErrMsg: "update: not allowed on primary key field Id: invalid field mask:", }, { name: "both are missing", @@ -303,7 +304,7 @@ func TestDb_Update(t *testing.T) { }, want: 0, wantErr: true, - wantErrMsg: "update: interface is missing invalid parameter", + wantErrMsg: "update: interface is missing invalid parameter:", }, { name: "only read-only", @@ -339,7 +340,7 @@ func TestDb_Update(t *testing.T) { if tt.wantErr { require.Error(err) assert.Equal(tt.want, rowsUpdated) - assert.Equal(tt.wantErrMsg, err.Error()) + assert.Contains(err.Error(), tt.wantErrMsg) return } require.NoError(err) @@ -443,7 +444,7 @@ func TestDb_Update(t *testing.T) { ) require.Error(err) assert.Equal(0, rowsUpdated) - assert.True(errors.Is(err, ErrInvalidParameter)) + assert.True(errors.Is(err, errors.ErrInvalidParameter)) }) t.Run("valid-NewOplogMsg", func(t *testing.T) { assert, require := assert.New(t), require.New(t) @@ -529,7 +530,7 @@ func TestDb_Update(t *testing.T) { rowsUpdated, err := w.Update(context.Background(), user, []string{"Name"}, nil) assert.Error(err) assert.Equal(0, rowsUpdated) - assert.Equal("update: missing underlying db invalid parameter", err.Error()) + assert.Contains(err.Error(), "update: missing underlying db invalid parameter:") }) t.Run("no-wrapper-WithOplog", func(t *testing.T) { assert, require := assert.New(t), require.New(t) @@ -551,7 +552,7 @@ func TestDb_Update(t *testing.T) { ) require.Error(err) assert.Equal(0, rowsUpdated) - assert.Equal("update: oplog validation failed: error no wrapper WithOplog: invalid parameter", err.Error()) + assert.Contains(err.Error(), "update: oplog validation failed: error no wrapper WithOplog: invalid parameter:") }) t.Run("no-metadata-WithOplog", func(t *testing.T) { assert, require := assert.New(t), require.New(t) @@ -568,7 +569,7 @@ func TestDb_Update(t *testing.T) { ) require.Error(err) assert.Equal(0, rowsUpdated) - assert.Equal("update: oplog validation failed: error no metadata for WithOplog: invalid parameter", err.Error()) + assert.Contains(err.Error(), "update: oplog validation failed: error no metadata for WithOplog: invalid parameter:") }) } @@ -590,20 +591,20 @@ func (u *testUserWithVet) TableName() string { } func (u *testUserWithVet) VetForWrite(ctx context.Context, r Reader, opType OpType, opt ...Option) error { if u.PublicId == "" { - return errors.New("public id is empty string for user write") + return stderrors.New("public id is empty string for user write") } if opType == UpdateOp { dbOptions := GetOpts(opt...) for _, path := range dbOptions.WithFieldMaskPaths { switch path { case "PublicId": - return errors.New("you cannot change the public id") + return stderrors.New("you cannot change the public id") } } } if opType == CreateOp { if u.Id != 0 { - return errors.New("id is a db sequence") + return stderrors.New("id is a db sequence") } } return nil @@ -683,7 +684,7 @@ func TestDb_Create(t *testing.T) { WithOplog(TestWrapper(t), oplog.Metadata{"alice": []string{"bob"}}), ) require.Error(err) - assert.True(errors.Is(err, ErrInvalidParameter)) + assert.True(errors.Is(err, errors.ErrInvalidParameter)) }) t.Run("valid-NewOplogMsg", func(t *testing.T) { assert, require := assert.New(t), require.New(t) @@ -749,7 +750,7 @@ func TestDb_Create(t *testing.T) { ), ) require.Error(err) - assert.Equal("create: oplog validation failed: error no wrapper WithOplog: invalid parameter", err.Error()) + assert.Contains(err.Error(), "create: oplog validation failed: error no wrapper WithOplog: invalid parameter") }) t.Run("no-metadata-WithOplog", func(t *testing.T) { assert, require := assert.New(t), require.New(t) @@ -768,7 +769,7 @@ func TestDb_Create(t *testing.T) { ), ) require.Error(err) - assert.Equal("create: oplog validation failed: error no metadata for WithOplog: invalid parameter", err.Error()) + assert.Contains(err.Error(), "create: oplog validation failed: error no metadata for WithOplog: invalid parameter") }) t.Run("nil-tx", func(t *testing.T) { assert, require := assert.New(t), require.New(t) @@ -780,7 +781,7 @@ func TestDb_Create(t *testing.T) { user.Name = "foo-" + id err = w.Create(context.Background(), user) require.Error(err) - assert.Equal("create: missing underlying db: invalid parameter", err.Error()) + assert.Contains(err.Error(), "create: missing underlying db: invalid parameter") }) } @@ -813,7 +814,7 @@ func TestDb_LookupByPublicId(t *testing.T) { require.NoError(err) err = w.LookupByPublicId(context.Background(), foundUser) require.Error(err) - assert.Equal("lookup by id: underlying db nil invalid parameter", err.Error()) + assert.Contains(err.Error(), "lookup by id: underlying db nil invalid parameter") }) t.Run("no-public-id-set", func(t *testing.T) { assert, require := assert.New(t), require.New(t) @@ -823,7 +824,7 @@ func TestDb_LookupByPublicId(t *testing.T) { require.NoError(err) err = w.LookupByPublicId(context.Background(), foundUser) require.Error(err) - assert.Equal("lookup by id: primary key unset invalid parameter", err.Error()) + assert.Contains(err.Error(), "lookup by id: primary key unset invalid parameter") }) t.Run("not-found", func(t *testing.T) { assert, require := assert.New(t), require.New(t) @@ -835,7 +836,7 @@ func TestDb_LookupByPublicId(t *testing.T) { foundUser.PublicId = id err = w.LookupByPublicId(context.Background(), foundUser) require.Error(err) - assert.Equal(ErrRecordNotFound, err) + assert.Equal(errors.ErrRecordNotFound, err) }) } @@ -876,8 +877,8 @@ func TestDb_LookupWhere(t *testing.T) { var foundUser db_test.TestUser err = w.LookupWhere(context.Background(), &foundUser, "public_id = ?", id) require.Error(err) - assert.Equal(ErrRecordNotFound, err) - assert.True(errors.Is(err, ErrRecordNotFound)) + assert.Equal(errors.ErrRecordNotFound, err) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) }) t.Run("bad-where", func(t *testing.T) { require := require.New(t) @@ -992,8 +993,6 @@ func TestDb_SearchWhere(t *testing.T) { assert.Equal(tt.createCnt, len(testUsers)) var foundUsers []db_test.TestUser - db.LogMode(true) - defer db.LogMode(false) err := tt.db.SearchWhere(context.Background(), &foundUsers, tt.args.where, tt.args.arg, tt.args.opt...) if tt.wantErr { require.Error(err) @@ -1119,7 +1118,7 @@ func TestDb_DoTx(t *testing.T) { t.Run("not-a-retry-err", func(t *testing.T) { assert, require := assert.New(t), require.New(t) w := &Db{underlying: db} - got, err := w.DoTx(context.Background(), 1, ExpBackoff{}, func(Reader, Writer) error { return errors.New("not a retry error") }) + got, err := w.DoTx(context.Background(), 1, ExpBackoff{}, func(Reader, Writer) error { return stderrors.New("not a retry error") }) require.Error(err) assert.Equal(RetryInfo{}, got) assert.NotEqual(err, oplog.ErrTicketAlreadyRedeemed) @@ -1274,7 +1273,7 @@ func TestDb_Delete(t *testing.T) { wantOplog: true, want: 0, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "nil-metadata", @@ -1287,7 +1286,7 @@ func TestDb_Delete(t *testing.T) { wantOplog: true, want: 0, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "nil-underlying", @@ -1298,7 +1297,7 @@ func TestDb_Delete(t *testing.T) { }, want: 0, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "not-found", @@ -1341,7 +1340,7 @@ func TestDb_Delete(t *testing.T) { foundUser.PublicId = tt.args.i.PublicId err = rw.LookupByPublicId(context.Background(), foundUser) assert.Error(err) - assert.Equal(ErrRecordNotFound, err) + assert.Equal(errors.ErrRecordNotFound, err) err = TestVerifyOplog(t, rw, tt.args.i.GetPublicId(), WithOperation(oplog.OpType_OP_TYPE_DELETE), WithCreateNotBefore(5*time.Second)) switch { @@ -1371,7 +1370,7 @@ func TestDb_Delete(t *testing.T) { rowsDeleted, err := w.Delete(context.Background(), user, NewOplogMsg(&deleteMsg), WithOplog(TestWrapper(t), oplog.Metadata{"alice": []string{"bob"}})) require.Error(err) assert.Equal(0, rowsDeleted) - assert.True(errors.Is(err, ErrInvalidParameter)) + assert.True(errors.Is(err, errors.ErrInvalidParameter)) }) t.Run("valid-NewOplogMsg", func(t *testing.T) { assert, require := assert.New(t), require.New(t) @@ -1403,7 +1402,7 @@ func TestDb_Delete(t *testing.T) { foundUser.PublicId = user.PublicId err = w.LookupByPublicId(context.Background(), foundUser) require.Error(err) - assert.True(errors.Is(err, ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) metadata := oplog.Metadata{ "resource-public-id": []string{user.PublicId}, @@ -1566,7 +1565,7 @@ func TestDb_CreateItems(t *testing.T) { ), }, }, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, wantErr: true, }, { @@ -1576,7 +1575,7 @@ func TestDb_CreateItems(t *testing.T) { createItems: createMixedFn(), }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "bad oplog opt: nil metadata", @@ -1591,7 +1590,7 @@ func TestDb_CreateItems(t *testing.T) { }, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "bad oplog opt: nil wrapper", @@ -1609,7 +1608,7 @@ func TestDb_CreateItems(t *testing.T) { }, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "bad opt: WithLookup", @@ -1619,7 +1618,7 @@ func TestDb_CreateItems(t *testing.T) { opt: []Option{WithLookup(true)}, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "nil underlying", @@ -1628,7 +1627,7 @@ func TestDb_CreateItems(t *testing.T) { createItems: createFn(), }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "empty items", @@ -1637,7 +1636,7 @@ func TestDb_CreateItems(t *testing.T) { createItems: []interface{}{}, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "nil items", @@ -1646,7 +1645,7 @@ func TestDb_CreateItems(t *testing.T) { createItems: nil, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -1754,7 +1753,7 @@ func TestDb_DeleteItems(t *testing.T) { }, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "withOplog", @@ -1788,7 +1787,7 @@ func TestDb_DeleteItems(t *testing.T) { }, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "bad oplog opt: nil wrapper", @@ -1806,7 +1805,7 @@ func TestDb_DeleteItems(t *testing.T) { }, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "bad opt: WithLookup", @@ -1816,7 +1815,7 @@ func TestDb_DeleteItems(t *testing.T) { opt: []Option{WithLookup(true)}, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "nil underlying", @@ -1825,7 +1824,7 @@ func TestDb_DeleteItems(t *testing.T) { deleteItems: createFn(), }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "empty items", @@ -1834,7 +1833,7 @@ func TestDb_DeleteItems(t *testing.T) { deleteItems: []interface{}{}, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "nil items", @@ -1843,7 +1842,7 @@ func TestDb_DeleteItems(t *testing.T) { deleteItems: nil, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -1867,7 +1866,7 @@ func TestDb_DeleteItems(t *testing.T) { u.PublicId = item.(*db_test.TestUser).PublicId err := rw.LookupByPublicId(context.Background(), &u) require.Error(err) - require.Truef(errors.Is(err, ErrRecordNotFound), "found item %s that should be deleted", u.PublicId) + require.Truef(errors.Is(err, errors.ErrRecordNotFound), "found item %s that should be deleted", u.PublicId) } if tt.wantOplogId != "" { err = TestVerifyOplog(t, rw, tt.wantOplogId, WithOperation(oplog.OpType_OP_TYPE_DELETE), WithCreateNotBefore(10*time.Second)) @@ -1996,7 +1995,7 @@ func TestDb_LookupById(t *testing.T) { }, }, wantErr: true, - wantIsErr: ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "missing-private-id", @@ -2007,7 +2006,7 @@ func TestDb_LookupById(t *testing.T) { }, }, wantErr: true, - wantIsErr: ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "not-an-ider", @@ -2016,7 +2015,7 @@ func TestDb_LookupById(t *testing.T) { resourceWithIder: &db_test.NotIder{}, }, wantErr: true, - wantIsErr: ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "missing-underlying-db", @@ -2025,7 +2024,7 @@ func TestDb_LookupById(t *testing.T) { resourceWithIder: user, }, wantErr: true, - wantIsErr: ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -2054,7 +2053,7 @@ func TestDb_LookupById(t *testing.T) { } err := rw.LookupById(context.Background(), *u) require.Error(t, err) - assert.True(t, errors.Is(err, ErrInvalidParameter)) + assert.True(t, errors.Is(err, errors.ErrInvalidParameter)) }) } @@ -2079,21 +2078,21 @@ func TestDb_GetTicket(t *testing.T) { underlying: db, aggregateType: ¬Replayable{}, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "nil-aggregate-type", underlying: db, aggregateType: nil, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "no-underlying", underlying: nil, aggregateType: &db_test.TestUser{}, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -2189,7 +2188,7 @@ func TestDb_WriteOplogEntryWith(t *testing.T) { msgs: []*oplog.Message{&createMsg}, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "missing-db", @@ -2201,7 +2200,7 @@ func TestDb_WriteOplogEntryWith(t *testing.T) { msgs: []*oplog.Message{&createMsg}, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "missing-wrapper", @@ -2213,7 +2212,7 @@ func TestDb_WriteOplogEntryWith(t *testing.T) { msgs: []*oplog.Message{&createMsg}, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "nil-metadata", @@ -2225,7 +2224,7 @@ func TestDb_WriteOplogEntryWith(t *testing.T) { msgs: []*oplog.Message{&createMsg}, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "empty-metadata", @@ -2237,7 +2236,7 @@ func TestDb_WriteOplogEntryWith(t *testing.T) { msgs: []*oplog.Message{&createMsg}, }, wantErr: true, - wantErrIs: ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -2289,7 +2288,7 @@ func TestClear_InputTypes(t *testing.T) { f: []string{"field"}, d: 1, }, - err: ErrInvalidParameter, + err: errors.ErrInvalidParameter, }, { name: "string", @@ -2298,7 +2297,7 @@ func TestClear_InputTypes(t *testing.T) { f: []string{"field"}, d: 1, }, - err: ErrInvalidParameter, + err: errors.ErrInvalidParameter, }, { name: "pointer-to-nil-struct", @@ -2307,7 +2306,7 @@ func TestClear_InputTypes(t *testing.T) { f: []string{"field"}, d: 1, }, - err: ErrInvalidParameter, + err: errors.ErrInvalidParameter, }, { name: "pointer-to-string", @@ -2316,7 +2315,7 @@ func TestClear_InputTypes(t *testing.T) { f: []string{"field"}, d: 1, }, - err: ErrInvalidParameter, + err: errors.ErrInvalidParameter, }, { name: "not-pointer", @@ -2327,7 +2326,7 @@ func TestClear_InputTypes(t *testing.T) { f: []string{"field"}, d: 1, }, - err: ErrInvalidParameter, + err: errors.ErrInvalidParameter, }, { name: "map", @@ -2339,7 +2338,7 @@ func TestClear_InputTypes(t *testing.T) { f: []string{"field"}, d: 1, }, - err: ErrInvalidParameter, + err: errors.ErrInvalidParameter, }, { name: "pointer-to-struct", @@ -2806,7 +2805,7 @@ func TestDb_oplogMsgsForItems(t *testing.T) { items: nil, }, wantErr: true, - wantIsErr: ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "zero items", @@ -2815,7 +2814,7 @@ func TestDb_oplogMsgsForItems(t *testing.T) { items: []interface{}{}, }, wantErr: true, - wantIsErr: ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "mixed items", @@ -2824,7 +2823,7 @@ func TestDb_oplogMsgsForItems(t *testing.T) { items: mixed, }, wantErr: true, - wantIsErr: ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "bad op", diff --git a/internal/errors/error_test.go b/internal/errors/error_test.go index 9299d125a..fcfe21b91 100644 --- a/internal/errors/error_test.go +++ b/internal/errors/error_test.go @@ -157,7 +157,7 @@ func TestError_Unwrap(t *testing.T) { Unwrap() error }).Unwrap() assert.Equal(tt.want, err) - assert.True(stderrors.Is(tt.err, tt.wantIsErr)) + assert.True(errors.Is(tt.err, tt.wantIsErr)) }) } t.Run("nil *Err", func(t *testing.T) { @@ -236,7 +236,7 @@ func TestConvertError(t *testing.T) { e := errors.Convert(err) require.NotNil(e) - assert.True(stderrors.Is(e, errors.ErrNotUnique)) + assert.True(errors.Is(e, errors.ErrNotUnique)) assert.Equal("Key (name)=(alice) already exists.: integrity violation: error #1002: \nunique constraint violation: integrity violation: error #1002", e.Error()) }) t.Run("ErrCodeNotNull", func(t *testing.T) { @@ -248,7 +248,7 @@ func TestConvertError(t *testing.T) { e := errors.Convert(err) require.NotNil(e) - assert.True(stderrors.Is(e, errors.ErrNotNull)) + assert.True(errors.Is(e, errors.ErrNotNull)) assert.Equal("description must not be empty: integrity violation: error #1001: \nnot null constraint violated: integrity violation: error #1001", e.Error()) }) t.Run("ErrCodeCheckConstraint", func(t *testing.T) { @@ -260,7 +260,7 @@ func TestConvertError(t *testing.T) { e := errors.Convert(err) require.NotNil(e) - assert.True(stderrors.Is(e, errors.ErrCheckConstraint)) + assert.True(errors.Is(e, errors.ErrCheckConstraint)) assert.Equal("test_table_five_check constraint failed: integrity violation: error #1000: \ncheck constraint violated: integrity violation: error #1000", e.Error()) }) t.Run("MissingTable", func(t *testing.T) { diff --git a/internal/host/static/host.go b/internal/host/static/host.go index ac025632f..8a7115b73 100644 --- a/internal/host/static/host.go +++ b/internal/host/static/host.go @@ -3,7 +3,7 @@ package static import ( "fmt" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/host/static/store" "github.com/hashicorp/boundary/internal/oplog" "google.golang.org/protobuf/proto" @@ -25,7 +25,7 @@ type Host struct { // ignored. func NewHost(catalogId string, opt ...Option) (*Host, error) { if catalogId == "" { - return nil, fmt.Errorf("new: static host: no catalog id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new: static host: no catalog id: %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) diff --git a/internal/host/static/host_catalog.go b/internal/host/static/host_catalog.go index e8c9f31e5..4c881955c 100644 --- a/internal/host/static/host_catalog.go +++ b/internal/host/static/host_catalog.go @@ -3,7 +3,7 @@ package static import ( "fmt" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/host/static/store" "github.com/hashicorp/boundary/internal/oplog" "google.golang.org/protobuf/proto" @@ -21,7 +21,7 @@ type HostCatalog struct { // ignored. func NewHostCatalog(scopeId string, opt ...Option) (*HostCatalog, error) { if scopeId == "" { - return nil, fmt.Errorf("new: static host catalog: no scope id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new: static host catalog: no scope id: %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) diff --git a/internal/host/static/host_set.go b/internal/host/static/host_set.go index 9ced6364e..39d40af34 100644 --- a/internal/host/static/host_set.go +++ b/internal/host/static/host_set.go @@ -3,7 +3,7 @@ package static import ( "fmt" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/host/static/store" "github.com/hashicorp/boundary/internal/oplog" "google.golang.org/protobuf/proto" @@ -20,7 +20,7 @@ type HostSet struct { // ignored. func NewHostSet(catalogId string, opt ...Option) (*HostSet, error) { if catalogId == "" { - return nil, fmt.Errorf("new: static host set: no catalog id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new: static host set: no catalog id: %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) diff --git a/internal/host/static/host_set_member.go b/internal/host/static/host_set_member.go index 2d125de05..287520ef4 100644 --- a/internal/host/static/host_set_member.go +++ b/internal/host/static/host_set_member.go @@ -3,7 +3,7 @@ package static import ( "fmt" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/host/static/store" ) @@ -17,10 +17,10 @@ type HostSetMember struct { // membership of hostId in hostSetId. func NewHostSetMember(hostSetId, hostId string, opt ...Option) (*HostSetMember, error) { if hostSetId == "" { - return nil, fmt.Errorf("new: static host set member: no host set id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new: static host set member: no host set id: %w", errors.ErrInvalidParameter) } if hostId == "" { - return nil, fmt.Errorf("new: static host set member: no host id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new: static host set member: no host id: %w", errors.ErrInvalidParameter) } member := &HostSetMember{ HostSetMember: &store.HostSetMember{ diff --git a/internal/host/static/repository.go b/internal/host/static/repository.go index bd7316441..e09e21937 100644 --- a/internal/host/static/repository.go +++ b/internal/host/static/repository.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" ) @@ -26,11 +27,11 @@ type Repository struct { func NewRepository(r db.Reader, w db.Writer, kms *kms.Kms, opt ...Option) (*Repository, error) { switch { case r == nil: - return nil, fmt.Errorf("db.Reader: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("db.Reader: %w", errors.ErrInvalidParameter) case w == nil: - return nil, fmt.Errorf("db.Writer: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("db.Writer: %w", errors.ErrInvalidParameter) case kms == nil: - return nil, fmt.Errorf("kms: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("kms: %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) diff --git a/internal/host/static/repository_host.go b/internal/host/static/repository_host.go index ade80c02b..d5e0817b8 100644 --- a/internal/host/static/repository_host.go +++ b/internal/host/static/repository_host.go @@ -2,12 +2,12 @@ package static import ( "context" - "errors" "fmt" "strings" "github.com/hashicorp/boundary/internal/db" dbcommon "github.com/hashicorp/boundary/internal/db/common" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" ) @@ -23,19 +23,19 @@ import ( // unique within h.CatalogId. func (r *Repository) CreateHost(ctx context.Context, scopeId string, h *Host, opt ...Option) (*Host, error) { if h == nil { - return nil, fmt.Errorf("create: static host: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: static host: %w", errors.ErrInvalidParameter) } if h.Host == nil { - return nil, fmt.Errorf("create: static host: embedded Host: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: static host: embedded Host: %w", errors.ErrInvalidParameter) } if h.CatalogId == "" { - return nil, fmt.Errorf("create: static host: no catalog id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: static host: no catalog id: %w", errors.ErrInvalidParameter) } if h.PublicId != "" { - return nil, fmt.Errorf("create: static host: public id not empty: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: static host: public id not empty: %w", errors.ErrInvalidParameter) } if scopeId == "" { - return nil, fmt.Errorf("create: static host: no scopeId: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: static host: no scopeId: %w", errors.ErrInvalidParameter) } h.Address = strings.TrimSpace(h.Address) if len(h.Address) < MinHostAddressLength || len(h.Address) > MaxHostAddressLength { @@ -47,7 +47,7 @@ func (r *Repository) CreateHost(ctx context.Context, scopeId string, h *Host, op if opts.withPublicId != "" { if !strings.HasPrefix(opts.withPublicId, HostPrefix+"_") { - return nil, fmt.Errorf("create: static host: passed-in public ID %q has wrong prefix, should be %q: %w", opts.withPublicId, HostPrefix, db.ErrInvalidPublicId) + return nil, fmt.Errorf("create: static host: passed-in public ID %q has wrong prefix, should be %q: %w", opts.withPublicId, HostPrefix, errors.ErrInvalidPublicId) } h.PublicId = opts.withPublicId } else { @@ -72,11 +72,11 @@ func (r *Repository) CreateHost(ctx context.Context, scopeId string, h *Host, op ) if err != nil { - if db.IsUniqueError(err) { + if errors.IsUniqueError(err) { return nil, fmt.Errorf("create: static host: in catalog: %s: name %s already exists: %w", - h.CatalogId, h.Name, db.ErrNotUnique) + h.CatalogId, h.Name, errors.ErrNotUnique) } - if db.IsCheckConstraintError(err) || db.IsNotNullError(err) { + if errors.IsCheckConstraintError(err) || errors.IsNotNullError(err) { return nil, fmt.Errorf("create: static host: in catalog: %s: %q: %w", h.CatalogId, h.Address, ErrInvalidAddress) } @@ -99,19 +99,19 @@ func (r *Repository) CreateHost(ctx context.Context, scopeId string, h *Host, op // in h is the zero value and it is included in fieldMaskPaths. func (r *Repository) UpdateHost(ctx context.Context, scopeId string, h *Host, version uint32, fieldMaskPaths []string, opt ...Option) (*Host, int, error) { if h == nil { - return nil, db.NoRowsAffected, fmt.Errorf("update: static host: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: static host: %w", errors.ErrInvalidParameter) } if h.Host == nil { - return nil, db.NoRowsAffected, fmt.Errorf("update: static host: embedded Host: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: static host: embedded Host: %w", errors.ErrInvalidParameter) } if h.PublicId == "" { - return nil, db.NoRowsAffected, fmt.Errorf("update: static host: missing public id: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: static host: missing public id: %w", errors.ErrInvalidParameter) } if version == 0 { - return nil, db.NoRowsAffected, fmt.Errorf("update: static host: no version supplied: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: static host: no version supplied: %w", errors.ErrInvalidParameter) } if scopeId == "" { - return nil, db.NoRowsAffected, fmt.Errorf("update: static host: no scopeId: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: static host: no scopeId: %w", errors.ErrInvalidParameter) } for _, f := range fieldMaskPaths { @@ -124,7 +124,7 @@ func (r *Repository) UpdateHost(ctx context.Context, scopeId string, h *Host, ve return nil, db.NoRowsAffected, fmt.Errorf("update: static host: bad address: %w", ErrInvalidAddress) } default: - return nil, db.NoRowsAffected, fmt.Errorf("update: static host: field: %s: %w", f, db.ErrInvalidFieldMask) + return nil, db.NoRowsAffected, fmt.Errorf("update: static host: field: %s: %w", f, errors.ErrInvalidFieldMask) } } var dbMask, nullFields []string @@ -138,7 +138,7 @@ func (r *Repository) UpdateHost(ctx context.Context, scopeId string, h *Host, ve nil, ) if len(dbMask) == 0 && len(nullFields) == 0 { - return nil, db.NoRowsAffected, fmt.Errorf("update: static host: %w", db.ErrEmptyFieldMask) + return nil, db.NoRowsAffected, fmt.Errorf("update: static host: %w", errors.ErrEmptyFieldMask) } oplogWrapper, err := r.kms.GetWrapper(ctx, scopeId, kms.KeyPurposeOplog) @@ -156,18 +156,18 @@ func (r *Repository) UpdateHost(ctx context.Context, scopeId string, h *Host, ve db.WithOplog(oplogWrapper, h.oplog(oplog.OpType_OP_TYPE_UPDATE)), db.WithVersion(&version)) if err == nil && rowsUpdated > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, ) if err != nil { - if db.IsUniqueError(err) { + if errors.IsUniqueError(err) { return nil, db.NoRowsAffected, fmt.Errorf("update: static host: %s: name %s already exists: %w", - h.PublicId, h.Name, db.ErrNotUnique) + h.PublicId, h.Name, errors.ErrNotUnique) } - if db.IsCheckConstraintError(err) || db.IsNotNullError(err) { + if errors.IsCheckConstraintError(err) || errors.IsNotNullError(err) { return nil, db.NoRowsAffected, fmt.Errorf("update: static host: %s: %q: %w", h.PublicId, h.Address, ErrInvalidAddress) } return nil, db.NoRowsAffected, fmt.Errorf("update: static host: %s: %w", h.PublicId, err) @@ -180,12 +180,12 @@ func (r *Repository) UpdateHost(ctx context.Context, scopeId string, h *Host, ve // found, it will return nil, nil. All options are ignored. func (r *Repository) LookupHost(ctx context.Context, publicId string, opt ...Option) (*Host, error) { if publicId == "" { - return nil, fmt.Errorf("lookup: static host: missing public id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup: static host: missing public id %w", errors.ErrInvalidParameter) } h := allocHost() h.PublicId = publicId if err := r.reader.LookupByPublicId(ctx, h); err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, nil } return nil, fmt.Errorf("lookup: static host: failed %w for %s", err, publicId) @@ -197,7 +197,7 @@ func (r *Repository) LookupHost(ctx context.Context, publicId string, opt ...Opt // WithLimit is the only option supported. func (r *Repository) ListHosts(ctx context.Context, catalogId string, opt ...Option) ([]*Host, error) { if catalogId == "" { - return nil, fmt.Errorf("list: static host: missing catalog id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list: static host: missing catalog id: %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) limit := r.defaultLimit @@ -218,7 +218,7 @@ func (r *Repository) ListHosts(ctx context.Context, catalogId string, opt ...Opt // ignored. func (r *Repository) DeleteHost(ctx context.Context, scopeId string, publicId string, opt ...Option) (int, error) { if publicId == "" { - return db.NoRowsAffected, fmt.Errorf("delete: static host: missing public id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete: static host: missing public id: %w", errors.ErrInvalidParameter) } h := allocHost() h.PublicId = publicId @@ -235,7 +235,7 @@ func (r *Repository) DeleteHost(ctx context.Context, scopeId string, publicId st dh := h.clone() rowsDeleted, err = w.Delete(ctx, dh, db.WithOplog(oplogWrapper, h.oplog(oplog.OpType_OP_TYPE_DELETE))) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, diff --git a/internal/host/static/repository_host_catalog.go b/internal/host/static/repository_host_catalog.go index 74efb4deb..6ba8ed674 100644 --- a/internal/host/static/repository_host_catalog.go +++ b/internal/host/static/repository_host_catalog.go @@ -2,11 +2,11 @@ package static import ( "context" - "errors" "fmt" "strings" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" ) @@ -22,16 +22,16 @@ import ( // Both c.CreateTime and c.UpdateTime are ignored. func (r *Repository) CreateCatalog(ctx context.Context, c *HostCatalog, opt ...Option) (*HostCatalog, error) { if c == nil { - return nil, fmt.Errorf("create: static host catalog: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: static host catalog: %w", errors.ErrInvalidParameter) } if c.HostCatalog == nil { - return nil, fmt.Errorf("create: static host catalog: embedded HostCatalog: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: static host catalog: embedded HostCatalog: %w", errors.ErrInvalidParameter) } if c.ScopeId == "" { - return nil, fmt.Errorf("create: static host catalog: no scope id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: static host catalog: no scope id: %w", errors.ErrInvalidParameter) } if c.PublicId != "" { - return nil, fmt.Errorf("create: static host catalog: public id not empty: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: static host catalog: public id not empty: %w", errors.ErrInvalidParameter) } c = c.clone() @@ -39,7 +39,7 @@ func (r *Repository) CreateCatalog(ctx context.Context, c *HostCatalog, opt ...O if opts.withPublicId != "" { if !strings.HasPrefix(opts.withPublicId, HostCatalogPrefix+"_") { - return nil, fmt.Errorf("create: static host catalog: passed-in public ID %q has wrong prefix, should be %q: %w", opts.withPublicId, HostCatalogPrefix, db.ErrInvalidPublicId) + return nil, fmt.Errorf("create: static host catalog: passed-in public ID %q has wrong prefix, should be %q: %w", opts.withPublicId, HostCatalogPrefix, errors.ErrInvalidPublicId) } c.PublicId = opts.withPublicId } else { @@ -73,9 +73,9 @@ func (r *Repository) CreateCatalog(ctx context.Context, c *HostCatalog, opt ...O ) if err != nil { - if db.IsUniqueError(err) { + if errors.IsUniqueError(err) { return nil, fmt.Errorf("create: static host catalog: in scope: %s: name %s already exists: %w", - c.ScopeId, c.Name, db.ErrNotUnique) + c.ScopeId, c.Name, errors.ErrNotUnique) } return nil, fmt.Errorf("create: static host catalog: in scope: %s: %w", c.ScopeId, err) } @@ -95,19 +95,19 @@ func (r *Repository) CreateCatalog(ctx context.Context, c *HostCatalog, opt ...O // in c is the zero value and it is included in fieldMask. func (r *Repository) UpdateCatalog(ctx context.Context, c *HostCatalog, version uint32, fieldMask []string, opt ...Option) (*HostCatalog, int, error) { if c == nil { - return nil, db.NoRowsAffected, fmt.Errorf("update: static host catalog: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: static host catalog: %w", errors.ErrInvalidParameter) } if c.HostCatalog == nil { - return nil, db.NoRowsAffected, fmt.Errorf("update: static host catalog: embedded HostCatalog: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: static host catalog: embedded HostCatalog: %w", errors.ErrInvalidParameter) } if c.PublicId == "" { - return nil, db.NoRowsAffected, fmt.Errorf("update: static host catalog: missing public id: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: static host catalog: missing public id: %w", errors.ErrInvalidParameter) } if c.ScopeId == "" { - return nil, db.NoRowsAffected, fmt.Errorf("update: static host catalog: missing scope id: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update: static host catalog: missing scope id: %w", errors.ErrInvalidParameter) } if len(fieldMask) == 0 { - return nil, db.NoRowsAffected, fmt.Errorf("update: static host catalog: %w", db.ErrEmptyFieldMask) + return nil, db.NoRowsAffected, fmt.Errorf("update: static host catalog: %w", errors.ErrEmptyFieldMask) } var dbMask, nullFields []string @@ -123,7 +123,7 @@ func (r *Repository) UpdateCatalog(ctx context.Context, c *HostCatalog, version dbMask = append(dbMask, "description") default: - return nil, db.NoRowsAffected, fmt.Errorf("update: static host catalog: field: %s: %w", f, db.ErrInvalidFieldMask) + return nil, db.NoRowsAffected, fmt.Errorf("update: static host catalog: field: %s: %w", f, errors.ErrInvalidFieldMask) } } @@ -154,16 +154,16 @@ func (r *Repository) UpdateCatalog(ctx context.Context, c *HostCatalog, version db.WithVersion(&version), ) if err == nil && rowsUpdated > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, ) if err != nil { - if db.IsUniqueError(err) { + if errors.IsUniqueError(err) { return nil, db.NoRowsAffected, fmt.Errorf("update: static host catalog: %s: name %s already exists: %w", - c.PublicId, c.Name, db.ErrNotUnique) + c.PublicId, c.Name, errors.ErrNotUnique) } return nil, db.NoRowsAffected, fmt.Errorf("update: static host catalog: %s: %w", c.PublicId, err) } @@ -175,12 +175,12 @@ func (r *Repository) UpdateCatalog(ctx context.Context, c *HostCatalog, version // HostCatalog is found for id. func (r *Repository) LookupCatalog(ctx context.Context, id string, opt ...Option) (*HostCatalog, error) { if id == "" { - return nil, fmt.Errorf("lookup: static host catalog: missing public id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup: static host catalog: missing public id: %w", errors.ErrInvalidParameter) } c := allocCatalog() c.PublicId = id if err := r.reader.LookupByPublicId(ctx, c); err != nil { - if err == db.ErrRecordNotFound { + if err == errors.ErrRecordNotFound { return nil, nil } return nil, fmt.Errorf("lookup: static host catalog: %s: %w", id, err) @@ -191,7 +191,7 @@ func (r *Repository) LookupCatalog(ctx context.Context, id string, opt ...Option // ListCatalogs returns a slice of HostCatalogs for the scopeId. WithLimit is the only option supported. func (r *Repository) ListCatalogs(ctx context.Context, scopeId string, opt ...Option) ([]*HostCatalog, error) { if scopeId == "" { - return nil, fmt.Errorf("list: static host catalog: missing scope id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list: static host catalog: missing scope id: %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) limit := r.defaultLimit @@ -211,19 +211,19 @@ func (r *Repository) ListCatalogs(ctx context.Context, scopeId string, opt ...Op // number of records deleted. func (r *Repository) DeleteCatalog(ctx context.Context, id string, opt ...Option) (int, error) { if id == "" { - return db.NoRowsAffected, fmt.Errorf("delete: static host catalog: missing public id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete: static host catalog: missing public id: %w", errors.ErrInvalidParameter) } c := allocCatalog() c.PublicId = id if err := r.reader.LookupByPublicId(ctx, c); err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return db.NoRowsAffected, nil } return db.NoRowsAffected, fmt.Errorf("delete: static host catalog: failed %w for %s", err, id) } if c.ScopeId == "" { - return db.NoRowsAffected, fmt.Errorf("delete: static host catalog: missing scope id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete: static host catalog: missing scope id: %w", errors.ErrInvalidParameter) } oplogWrapper, err := r.kms.GetWrapper(ctx, c.ScopeId, kms.KeyPurposeOplog) if err != nil { @@ -247,7 +247,7 @@ func (r *Repository) DeleteCatalog(ctx context.Context, id string, opt ...Option db.WithOplog(oplogWrapper, metadata), ) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, diff --git a/internal/host/static/repository_host_catalog_test.go b/internal/host/static/repository_host_catalog_test.go index 2ab4586e4..26bd26fa8 100644 --- a/internal/host/static/repository_host_catalog_test.go +++ b/internal/host/static/repository_host_catalog_test.go @@ -2,12 +2,12 @@ package static import ( "context" - "errors" "strings" "testing" "github.com/hashicorp/boundary/internal/db" dbassert "github.com/hashicorp/boundary/internal/db/assert" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/host/static/store" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" @@ -29,12 +29,12 @@ func TestRepository_CreateCatalog(t *testing.T) { }{ { name: "nil-catalog", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-embedded-catalog", in: &HostCatalog{}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid-no-options", @@ -127,7 +127,7 @@ func TestRepository_CreateCatalog(t *testing.T) { assert.Equal(got.CreateTime, got.UpdateTime) got2, err := repo.CreateCatalog(context.Background(), in) - assert.Truef(errors.Is(err, db.ErrNotUnique), "want err: %v got: %v", db.ErrNotUnique, err) + assert.Truef(errors.Is(err, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err) assert.Nil(got2) }) @@ -245,7 +245,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { }, chgFn: makeNil(), masks: []string{"Name", "Description"}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-embedded-catalog", @@ -254,7 +254,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { }, chgFn: makeEmbeddedNil(), masks: []string{"Name", "Description"}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "no-public-id", @@ -263,7 +263,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { }, chgFn: deletePublicId(), masks: []string{"Name", "Description"}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "updating-non-existent-catalog", @@ -274,7 +274,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { }, chgFn: combine(nonExistentPublicId(), changeName("test-update-name-repo")), masks: []string{"Name"}, - wantIsErr: db.ErrRecordNotFound, + wantIsErr: errors.ErrRecordNotFound, }, { name: "empty-field-mask", @@ -284,7 +284,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { }, }, chgFn: changeName("test-update-name-repo"), - wantIsErr: db.ErrEmptyFieldMask, + wantIsErr: errors.ErrEmptyFieldMask, }, { name: "read-only-fields-in-field-mask", @@ -295,7 +295,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { }, chgFn: changeName("test-update-name-repo"), masks: []string{"PublicId", "CreateTime", "UpdateTime", "ScopeId"}, - wantIsErr: db.ErrInvalidFieldMask, + wantIsErr: errors.ErrInvalidFieldMask, }, { name: "unknown-field-in-field-mask", @@ -306,7 +306,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { }, chgFn: changeName("test-update-name-repo"), masks: []string{"Bilbo"}, - wantIsErr: db.ErrInvalidFieldMask, + wantIsErr: errors.ErrInvalidFieldMask, }, { name: "change-name", @@ -496,7 +496,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { c2 := cats[1] c2.Name = name got2, gotCount2, err := repo.UpdateCatalog(context.Background(), c2, 1, []string{"name"}) - assert.Truef(errors.Is(err, db.ErrNotUnique), "want err: %v got: %v", db.ErrNotUnique, err) + assert.Truef(errors.Is(err, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err) assert.Nil(got2) assert.Equal(db.NoRowsAffected, gotCount2, "row count") }) @@ -595,7 +595,7 @@ func TestRepository_LookupCatalog(t *testing.T) { name: "bad-public-id", id: "", want: nil, - wantErr: db.ErrInvalidParameter, + wantErr: errors.ErrInvalidParameter, }, } @@ -657,7 +657,7 @@ func TestRepository_DeleteCatalog(t *testing.T) { name: "bad-public-id", id: "", want: 0, - wantErr: db.ErrInvalidParameter, + wantErr: errors.ErrInvalidParameter, }, } diff --git a/internal/host/static/repository_host_set.go b/internal/host/static/repository_host_set.go index 29e43090c..476c208bf 100644 --- a/internal/host/static/repository_host_set.go +++ b/internal/host/static/repository_host_set.go @@ -2,12 +2,12 @@ package static import ( "context" - "errors" "fmt" "strings" "github.com/hashicorp/boundary/internal/db" dbcommon "github.com/hashicorp/boundary/internal/db/common" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" ) @@ -21,19 +21,19 @@ import ( // unique within s.CatalogId. func (r *Repository) CreateSet(ctx context.Context, scopeId string, s *HostSet, opt ...Option) (*HostSet, error) { if s == nil { - return nil, fmt.Errorf("create: static host set: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: static host set: %w", errors.ErrInvalidParameter) } if s.HostSet == nil { - return nil, fmt.Errorf("create: static host set: embedded HostSet: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: static host set: embedded HostSet: %w", errors.ErrInvalidParameter) } if s.CatalogId == "" { - return nil, fmt.Errorf("create: static host set: no catalog id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: static host set: no catalog id: %w", errors.ErrInvalidParameter) } if s.PublicId != "" { - return nil, fmt.Errorf("create: static host set: public id not empty: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: static host set: public id not empty: %w", errors.ErrInvalidParameter) } if scopeId == "" { - return nil, fmt.Errorf("create: static host set: no scopeId: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create: static host set: no scopeId: %w", errors.ErrInvalidParameter) } s = s.clone() @@ -41,7 +41,7 @@ func (r *Repository) CreateSet(ctx context.Context, scopeId string, s *HostSet, if opts.withPublicId != "" { if !strings.HasPrefix(opts.withPublicId, HostSetPrefix+"_") { - return nil, fmt.Errorf("create: static host set: passed-in public ID %q has wrong prefix, should be %q: %w", opts.withPublicId, HostSetPrefix, db.ErrInvalidPublicId) + return nil, fmt.Errorf("create: static host set: passed-in public ID %q has wrong prefix, should be %q: %w", opts.withPublicId, HostSetPrefix, errors.ErrInvalidPublicId) } s.PublicId = opts.withPublicId } else { @@ -66,9 +66,9 @@ func (r *Repository) CreateSet(ctx context.Context, scopeId string, s *HostSet, ) if err != nil { - if db.IsUniqueError(err) { + if errors.IsUniqueError(err) { return nil, fmt.Errorf("create: static host set: in catalog: %s: name %s already exists: %w", - s.CatalogId, s.Name, db.ErrNotUnique) + s.CatalogId, s.Name, errors.ErrNotUnique) } return nil, fmt.Errorf("create: static host set: in catalog: %s: %w", s.CatalogId, err) } @@ -91,19 +91,19 @@ func (r *Repository) CreateSet(ctx context.Context, scopeId string, s *HostSet, // All other options are ignored. func (r *Repository) UpdateSet(ctx context.Context, scopeId string, s *HostSet, version uint32, fieldMaskPaths []string, opt ...Option) (*HostSet, []*Host, int, error) { if s == nil { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: %w", errors.ErrInvalidParameter) } if s.HostSet == nil { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: embedded HostSet: %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: embedded HostSet: %w", errors.ErrInvalidParameter) } if s.PublicId == "" { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: missing public id: %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: missing public id: %w", errors.ErrInvalidParameter) } if version == 0 { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: no version supplied: %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: no version supplied: %w", errors.ErrInvalidParameter) } if scopeId == "" { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: no scopeId: %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: no scopeId: %w", errors.ErrInvalidParameter) } for _, f := range fieldMaskPaths { @@ -111,7 +111,7 @@ func (r *Repository) UpdateSet(ctx context.Context, scopeId string, s *HostSet, case strings.EqualFold("Name", f): case strings.EqualFold("Description", f): default: - return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: field: %s: %w", f, db.ErrInvalidFieldMask) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: field: %s: %w", f, errors.ErrInvalidFieldMask) } } var dbMask, nullFields []string @@ -124,7 +124,7 @@ func (r *Repository) UpdateSet(ctx context.Context, scopeId string, s *HostSet, nil, ) if len(dbMask) == 0 && len(nullFields) == 0 { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: %w", db.ErrEmptyFieldMask) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: %w", errors.ErrEmptyFieldMask) } opts := getOpts(opt...) @@ -150,7 +150,7 @@ func (r *Repository) UpdateSet(ctx context.Context, scopeId string, s *HostSet, db.WithOplog(oplogWrapper, s.oplog(oplog.OpType_OP_TYPE_UPDATE)), db.WithVersion(&version)) if err == nil && rowsUpdated > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } if err != nil { return err @@ -161,9 +161,9 @@ func (r *Repository) UpdateSet(ctx context.Context, scopeId string, s *HostSet, ) if err != nil { - if db.IsUniqueError(err) { + if errors.IsUniqueError(err) { return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: %s: name %s already exists: %w", - s.PublicId, s.Name, db.ErrNotUnique) + s.PublicId, s.Name, errors.ErrNotUnique) } return nil, nil, db.NoRowsAffected, fmt.Errorf("update: static host set: %s: %w", s.PublicId, err) } @@ -177,7 +177,7 @@ func (r *Repository) UpdateSet(ctx context.Context, scopeId string, s *HostSet, // limit the number of hosts returned. All other options are ignored. func (r *Repository) LookupSet(ctx context.Context, publicId string, opt ...Option) (*HostSet, []*Host, error) { if publicId == "" { - return nil, nil, fmt.Errorf("lookup: static host set: missing public id %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("lookup: static host set: missing public id %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) limit := r.defaultLimit @@ -192,7 +192,7 @@ func (r *Repository) LookupSet(ctx context.Context, publicId string, opt ...Opti var hosts []*Host _, err := r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{}, func(reader db.Reader, _ db.Writer) error { if err := reader.LookupByPublicId(ctx, s); err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { s = nil return nil } @@ -214,7 +214,7 @@ func (r *Repository) LookupSet(ctx context.Context, publicId string, opt ...Opti // only option supported. func (r *Repository) ListSets(ctx context.Context, catalogId string, opt ...Option) ([]*HostSet, error) { if catalogId == "" { - return nil, fmt.Errorf("list: static host set: missing catalog id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list: static host set: missing catalog id: %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) limit := r.defaultLimit @@ -235,10 +235,10 @@ func (r *Repository) ListSets(ctx context.Context, catalogId string, opt ...Opti // ignored. func (r *Repository) DeleteSet(ctx context.Context, scopeId string, publicId string, opt ...Option) (int, error) { if publicId == "" { - return db.NoRowsAffected, fmt.Errorf("delete: static host set: missing public id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete: static host set: missing public id: %w", errors.ErrInvalidParameter) } if scopeId == "" { - return db.NoRowsAffected, fmt.Errorf("delete: static host set: no scopeId: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete: static host set: no scopeId: %w", errors.ErrInvalidParameter) } s := allocHostSet() s.PublicId = publicId @@ -255,7 +255,7 @@ func (r *Repository) DeleteSet(ctx context.Context, scopeId string, publicId str ds := s.clone() rowsDeleted, err = w.Delete(ctx, ds, db.WithOplog(oplogWrapper, s.oplog(oplog.OpType_OP_TYPE_DELETE))) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, diff --git a/internal/host/static/repository_host_set_member.go b/internal/host/static/repository_host_set_member.go index ec2be73f1..9f394356c 100644 --- a/internal/host/static/repository_host_set_member.go +++ b/internal/host/static/repository_host_set_member.go @@ -8,6 +8,7 @@ import ( wrapping "github.com/hashicorp/go-kms-wrapping" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" ) @@ -18,16 +19,16 @@ import ( // setId in the repository. func (r *Repository) AddSetMembers(ctx context.Context, scopeId string, setId string, version uint32, hostIds []string, opt ...Option) ([]*Host, error) { if scopeId == "" { - return nil, fmt.Errorf("add: static host set members: missing scope id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("add: static host set members: missing scope id: %w", errors.ErrInvalidParameter) } if setId == "" { - return nil, fmt.Errorf("add: static host set members: missing set id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("add: static host set members: missing set id: %w", errors.ErrInvalidParameter) } if version == 0 { - return nil, fmt.Errorf("add: static host set members: version is zero: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("add: static host set members: version is zero: %w", errors.ErrInvalidParameter) } if len(hostIds) == 0 { - return nil, fmt.Errorf("add: static host set members: empty hostIds: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("add: static host set members: empty hostIds: %w", errors.ErrInvalidParameter) } // Create in-memory host set members @@ -94,7 +95,7 @@ func updateVersion(ctx context.Context, w db.Writer, wrapper wrapping.Wrapper, m case err != nil: return fmt.Errorf("unable to update host set version: %w", err) case rowsUpdated > 1: - return fmt.Errorf("unable to update host set version: %w", db.ErrMultipleRecords) + return fmt.Errorf("unable to update host set version: %w", errors.ErrMultipleRecords) } msgs = append(msgs, setMsg) @@ -154,16 +155,16 @@ func getHosts(ctx context.Context, reader db.Reader, setId string, limit int) ([ // the current version of the setId in the repository. func (r *Repository) DeleteSetMembers(ctx context.Context, scopeId string, setId string, version uint32, hostIds []string, opt ...Option) (int, error) { if scopeId == "" { - return db.NoRowsAffected, fmt.Errorf("delete: static host set members: missing scope id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete: static host set members: missing scope id: %w", errors.ErrInvalidParameter) } if setId == "" { - return db.NoRowsAffected, fmt.Errorf("delete: static host set members: missing set id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete: static host set members: missing set id: %w", errors.ErrInvalidParameter) } if version == 0 { - return db.NoRowsAffected, fmt.Errorf("delete: static host set members: version is zero: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete: static host set members: version is zero: %w", errors.ErrInvalidParameter) } if len(hostIds) == 0 { - return db.NoRowsAffected, fmt.Errorf("delete: static host set members: empty hostIds: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete: static host set members: empty hostIds: %w", errors.ErrInvalidParameter) } // Create in-memory host set members @@ -216,13 +217,13 @@ func deleteMembers(ctx context.Context, w db.Writer, members []interface{}) ([]* // in the repository. If hostIds is empty, all hosts will be removed setId. func (r *Repository) SetSetMembers(ctx context.Context, scopeId string, setId string, version uint32, hostIds []string, opt ...Option) ([]*Host, int, error) { if scopeId == "" { - return nil, db.NoRowsAffected, fmt.Errorf("set: static host set members: missing scope id: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("set: static host set members: missing scope id: %w", errors.ErrInvalidParameter) } if setId == "" { - return nil, db.NoRowsAffected, fmt.Errorf("set: static host set members: missing set id: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("set: static host set members: missing set id: %w", errors.ErrInvalidParameter) } if version == 0 { - return nil, db.NoRowsAffected, fmt.Errorf("set: static host set members: version is zero: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("set: static host set members: version is zero: %w", errors.ErrInvalidParameter) } // TODO(mgaffney) 08/2020: Oplog does not currently support bulk diff --git a/internal/host/static/repository_host_set_member_test.go b/internal/host/static/repository_host_set_member_test.go index 2b9050c2c..1dc53430f 100644 --- a/internal/host/static/repository_host_set_member_test.go +++ b/internal/host/static/repository_host_set_member_test.go @@ -2,13 +2,13 @@ package static import ( "context" - "errors" "testing" "time" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -57,7 +57,7 @@ func TestRepository_AddSetMembers_Parameters(t *testing.T) { version: set.Version, hostIds: hostIds, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-set-id", @@ -66,7 +66,7 @@ func TestRepository_AddSetMembers_Parameters(t *testing.T) { version: set.Version, hostIds: hostIds, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "zero-version", @@ -75,7 +75,7 @@ func TestRepository_AddSetMembers_Parameters(t *testing.T) { setId: set.PublicId, hostIds: hostIds, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-host-ids", @@ -84,7 +84,7 @@ func TestRepository_AddSetMembers_Parameters(t *testing.T) { setId: set.PublicId, version: set.Version, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-version", @@ -248,7 +248,7 @@ func TestRepository_DeleteSetMembers_Parameters(t *testing.T) { version: set.Version, hostIds: hostIds, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-set-id", @@ -257,7 +257,7 @@ func TestRepository_DeleteSetMembers_Parameters(t *testing.T) { version: set.Version, hostIds: hostIds, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "zero-version", @@ -266,7 +266,7 @@ func TestRepository_DeleteSetMembers_Parameters(t *testing.T) { setId: set.PublicId, hostIds: hostIds, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-host-ids", @@ -275,7 +275,7 @@ func TestRepository_DeleteSetMembers_Parameters(t *testing.T) { setId: set.PublicId, version: set.Version, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-version", @@ -446,7 +446,7 @@ func TestRepository_SetSetMembers_Parameters(t *testing.T) { version: set.Version, hostIds: hostIds, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-set-id", @@ -455,7 +455,7 @@ func TestRepository_SetSetMembers_Parameters(t *testing.T) { version: set.Version, hostIds: hostIds, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "zero-version", @@ -464,7 +464,7 @@ func TestRepository_SetSetMembers_Parameters(t *testing.T) { setId: set.PublicId, hostIds: hostIds, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-version", diff --git a/internal/host/static/repository_host_set_test.go b/internal/host/static/repository_host_set_test.go index de0492809..baac89d7d 100644 --- a/internal/host/static/repository_host_set_test.go +++ b/internal/host/static/repository_host_set_test.go @@ -2,7 +2,6 @@ package static import ( "context" - "errors" "testing" "time" @@ -10,6 +9,7 @@ import ( "github.com/google/go-cmp/cmp/cmpopts" "github.com/hashicorp/boundary/internal/db" dbassert "github.com/hashicorp/boundary/internal/db/assert" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/host/static/store" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" @@ -37,19 +37,19 @@ func TestRepository_CreateSet(t *testing.T) { }{ { name: "nil-HostSet", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-embedded-HostSet", in: &HostSet{}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-no-catalog-id", in: &HostSet{ HostSet: &store.HostSet{}, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-public-id-set", @@ -59,7 +59,7 @@ func TestRepository_CreateSet(t *testing.T) { PublicId: "abcd_OOOOOOOOOO", }, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid-no-options", @@ -157,7 +157,7 @@ func TestRepository_CreateSet(t *testing.T) { assert.Equal(got.CreateTime, got.UpdateTime) got2, err := repo.CreateSet(context.Background(), prj.GetPublicId(), in) - assert.Truef(errors.Is(err, db.ErrNotUnique), "want err: %v got: %v", db.ErrNotUnique, err) + assert.Truef(errors.Is(err, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err) assert.Nil(got2) }) @@ -273,7 +273,7 @@ func TestRepository_UpdateSet(t *testing.T) { }, chgFn: makeNil(), masks: []string{"Name", "Description"}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-embedded-host-set", @@ -282,7 +282,7 @@ func TestRepository_UpdateSet(t *testing.T) { }, chgFn: makeEmbeddedNil(), masks: []string{"Name", "Description"}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "no-public-id", @@ -291,7 +291,7 @@ func TestRepository_UpdateSet(t *testing.T) { }, chgFn: deletePublicId(), masks: []string{"Name", "Description"}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "updating-non-existent-host-set", @@ -302,7 +302,7 @@ func TestRepository_UpdateSet(t *testing.T) { }, chgFn: combine(nonExistentPublicId(), changeName("test-update-name-repo")), masks: []string{"Name"}, - wantIsErr: db.ErrRecordNotFound, + wantIsErr: errors.ErrRecordNotFound, }, { name: "empty-field-mask", @@ -312,7 +312,7 @@ func TestRepository_UpdateSet(t *testing.T) { }, }, chgFn: changeName("test-update-name-repo"), - wantIsErr: db.ErrEmptyFieldMask, + wantIsErr: errors.ErrEmptyFieldMask, }, { name: "read-only-fields-in-field-mask", @@ -323,7 +323,7 @@ func TestRepository_UpdateSet(t *testing.T) { }, chgFn: changeName("test-update-name-repo"), masks: []string{"PublicId", "CreateTime", "UpdateTime", "CatalogId"}, - wantIsErr: db.ErrInvalidFieldMask, + wantIsErr: errors.ErrInvalidFieldMask, }, { name: "unknown-field-in-field-mask", @@ -334,7 +334,7 @@ func TestRepository_UpdateSet(t *testing.T) { }, chgFn: changeName("test-update-name-repo"), masks: []string{"Bilbo"}, - wantIsErr: db.ErrInvalidFieldMask, + wantIsErr: errors.ErrInvalidFieldMask, }, { name: "change-name", @@ -540,12 +540,12 @@ func TestRepository_UpdateSet(t *testing.T) { sB.Name = name got2, gotHosts, gotCount2, err := repo.UpdateSet(context.Background(), prj.GetPublicId(), sB, 1, []string{"name"}) - assert.Truef(errors.Is(err, db.ErrNotUnique), "want err: %v got: %v", db.ErrNotUnique, err) + assert.Truef(errors.Is(err, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err) assert.Nil(got2) assert.Equal(db.NoRowsAffected, gotCount2, "row count") err = db.TestVerifyOplog(t, rw, sB.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) assert.Empty(gotHosts) }) @@ -728,7 +728,7 @@ func TestRepository_LookupSet(t *testing.T) { }{ { name: "with-no-public-id", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "with-non-existing-host-set-id", @@ -868,7 +868,7 @@ func TestRepository_ListSets(t *testing.T) { }{ { name: "with-no-catalog-id", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "Catalog-with-no-host-sets", @@ -996,7 +996,7 @@ func TestRepository_DeleteSet(t *testing.T) { }{ { name: "With no public id", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "With non existing host set id", diff --git a/internal/host/static/repository_host_test.go b/internal/host/static/repository_host_test.go index 03201cc51..06fc342d4 100644 --- a/internal/host/static/repository_host_test.go +++ b/internal/host/static/repository_host_test.go @@ -2,7 +2,6 @@ package static import ( "context" - "errors" "testing" "time" @@ -10,6 +9,7 @@ import ( "github.com/google/go-cmp/cmp/cmpopts" "github.com/hashicorp/boundary/internal/db" dbassert "github.com/hashicorp/boundary/internal/db/assert" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/host/static/store" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" @@ -37,19 +37,19 @@ func TestRepository_CreateHost(t *testing.T) { }{ { name: "nil-Host", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-embedded-Host", in: &Host{}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-no-catalog-id", in: &Host{ Host: &store.Host{}, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-public-id-set", @@ -60,7 +60,7 @@ func TestRepository_CreateHost(t *testing.T) { Address: "127.0.0.1", }, }, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid-no-options", @@ -194,7 +194,7 @@ func TestRepository_CreateHost(t *testing.T) { assert.Equal(got.CreateTime, got.UpdateTime) got2, err := repo.CreateHost(context.Background(), prj.GetPublicId(), in) - assert.Truef(errors.Is(err, db.ErrNotUnique), "want err: %v got: %v", db.ErrNotUnique, err) + assert.Truef(errors.Is(err, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err) assert.Nil(got2) }) @@ -320,7 +320,7 @@ func TestRepository_UpdateHost(t *testing.T) { }, chgFn: makeNil(), masks: []string{"Name", "Description"}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-embedded-host", @@ -331,7 +331,7 @@ func TestRepository_UpdateHost(t *testing.T) { }, chgFn: makeEmbeddedNil(), masks: []string{"Name", "Description"}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "no-public-id", @@ -342,7 +342,7 @@ func TestRepository_UpdateHost(t *testing.T) { }, chgFn: deletePublicId(), masks: []string{"Name", "Description"}, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "updating-non-existent-host", @@ -354,7 +354,7 @@ func TestRepository_UpdateHost(t *testing.T) { }, chgFn: combine(nonExistentPublicId(), changeName("test-update-name-repo")), masks: []string{"Name"}, - wantIsErr: db.ErrRecordNotFound, + wantIsErr: errors.ErrRecordNotFound, }, { name: "empty-field-mask", @@ -365,7 +365,7 @@ func TestRepository_UpdateHost(t *testing.T) { }, }, chgFn: changeName("test-update-name-repo"), - wantIsErr: db.ErrEmptyFieldMask, + wantIsErr: errors.ErrEmptyFieldMask, }, { name: "read-only-fields-in-field-mask", @@ -377,7 +377,7 @@ func TestRepository_UpdateHost(t *testing.T) { }, chgFn: changeName("test-update-name-repo"), masks: []string{"PublicId", "CreateTime", "UpdateTime", "CatalogId"}, - wantIsErr: db.ErrInvalidFieldMask, + wantIsErr: errors.ErrInvalidFieldMask, }, { name: "unknown-field-in-field-mask", @@ -389,7 +389,7 @@ func TestRepository_UpdateHost(t *testing.T) { }, chgFn: changeName("test-update-name-repo"), masks: []string{"Bilbo"}, - wantIsErr: db.ErrInvalidFieldMask, + wantIsErr: errors.ErrInvalidFieldMask, }, { name: "change-name", @@ -649,12 +649,12 @@ func TestRepository_UpdateHost(t *testing.T) { hB.Name = name got2, gotCount2, err := repo.UpdateHost(context.Background(), prj.GetPublicId(), hB, 1, []string{"name"}) - assert.Truef(errors.Is(err, db.ErrNotUnique), "want err: %v got: %v", db.ErrNotUnique, err) + assert.Truef(errors.Is(err, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err) assert.Nil(got2) assert.Equal(db.NoRowsAffected, gotCount2, "row count") err = db.TestVerifyOplog(t, rw, hB.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) t.Run("valid-duplicate-names-diff-Catalogs", func(t *testing.T) { @@ -752,7 +752,7 @@ func TestRepository_LookupHost(t *testing.T) { }{ { name: "with-no-public-id", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "with-non-existing-host-id", @@ -806,7 +806,7 @@ func TestRepository_ListHosts(t *testing.T) { }{ { name: "with-no-catalog-id", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "Catalog-with-no-hosts", @@ -934,7 +934,7 @@ func TestRepository_DeleteHost(t *testing.T) { }{ { name: "With no public id", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "With non existing host id", diff --git a/internal/host/static/repository_test.go b/internal/host/static/repository_test.go index e144011e2..0e4f59b36 100644 --- a/internal/host/static/repository_test.go +++ b/internal/host/static/repository_test.go @@ -1,13 +1,13 @@ package static import ( - "errors" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" ) @@ -67,7 +67,7 @@ func TestRepository_New(t *testing.T) { kms: kmsCache, }, want: nil, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-writer", @@ -77,7 +77,7 @@ func TestRepository_New(t *testing.T) { kms: kmsCache, }, want: nil, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-kms", @@ -87,7 +87,7 @@ func TestRepository_New(t *testing.T) { kms: nil, }, want: nil, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "all-nils", @@ -97,7 +97,7 @@ func TestRepository_New(t *testing.T) { kms: nil, }, want: nil, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, } for _, tt := range tests { diff --git a/internal/iam/account.go b/internal/iam/account.go index d59a0ff13..1d4234e59 100644 --- a/internal/iam/account.go +++ b/internal/iam/account.go @@ -6,6 +6,7 @@ import ( authStore "github.com/hashicorp/boundary/internal/auth/store" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/oplog" "github.com/hashicorp/boundary/internal/types/scope" "google.golang.org/protobuf/proto" @@ -43,7 +44,7 @@ func (a *authAccount) Clone() interface{} { // VetForWrite implements db.VetForWrite() interface. func (a *authAccount) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if a.PublicId == "" { - return fmt.Errorf("error public id is empty string for auth account write: %w", db.ErrInvalidParameter) + return fmt.Errorf("error public id is empty string for auth account write: %w", errors.ErrInvalidParameter) } if err := validateScopeForWrite(ctx, r, a, opType, opt...); err != nil { return err diff --git a/internal/iam/group.go b/internal/iam/group.go index 44e7ca989..b11e1d3c2 100644 --- a/internal/iam/group.go +++ b/internal/iam/group.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam/store" "github.com/hashicorp/boundary/internal/types/action" "github.com/hashicorp/boundary/internal/types/resource" @@ -31,7 +32,7 @@ var _ db.VetForWriter = (*Group)(nil) // and allowed options include: withDescripion, WithName. func NewGroup(scopeId string, opt ...Option) (*Group, error) { if scopeId == "" { - return nil, fmt.Errorf("new group: missing scope id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new group: missing scope id %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) g := &Group{ @@ -62,7 +63,7 @@ func allocGroup() Group { // before it's written. func (g *Group) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if g.PublicId == "" { - return fmt.Errorf("group vet for write: missing public id: %w", db.ErrInvalidParameter) + return fmt.Errorf("group vet for write: missing public id: %w", errors.ErrInvalidParameter) } if err := validateScopeForWrite(ctx, r, g, opType, opt...); err != nil { return err diff --git a/internal/iam/group_member.go b/internal/iam/group_member.go index 4d31d5aad..ad3889ece 100644 --- a/internal/iam/group_member.go +++ b/internal/iam/group_member.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam/store" "google.golang.org/protobuf/proto" ) @@ -70,10 +71,10 @@ var _ db.VetForWriter = (*GroupMemberUser)(nil) // options are currently supported. func NewGroupMemberUser(groupId, userId string, opt ...Option) (*GroupMemberUser, error) { if groupId == "" { - return nil, fmt.Errorf("new group member: missing group id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new group member: missing group id: %w", errors.ErrInvalidParameter) } if userId == "" { - return nil, fmt.Errorf("new group member: missing user id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new group member: missing user id: %w", errors.ErrInvalidParameter) } return &GroupMemberUser{ GroupMemberUser: &store.GroupMemberUser{ @@ -100,10 +101,10 @@ func (m *GroupMemberUser) Clone() interface{} { // VetForWrite implements db.VetForWrite() interface for group members. func (m *GroupMemberUser) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if m.GroupId == "" { - return fmt.Errorf("group member: missing group id: %w", db.ErrInvalidParameter) + return fmt.Errorf("group member: missing group id: %w", errors.ErrInvalidParameter) } if m.MemberId == "" { - return fmt.Errorf("group member: missing member id: %w", db.ErrInvalidParameter) + return fmt.Errorf("group member: missing member id: %w", errors.ErrInvalidParameter) } return nil } diff --git a/internal/iam/group_member_test.go b/internal/iam/group_member_test.go index 2bad5e64e..444a49189 100644 --- a/internal/iam/group_member_test.go +++ b/internal/iam/group_member_test.go @@ -2,10 +2,10 @@ package iam import ( "context" - "errors" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam/store" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -83,7 +83,7 @@ func Test_NewGroupMember(t *testing.T) { }, want: nil, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "missing-user", @@ -92,7 +92,7 @@ func Test_NewGroupMember(t *testing.T) { }, want: nil, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -196,7 +196,7 @@ func Test_GroupMemberCreate(t *testing.T) { }(), }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "missing-user-id", @@ -212,7 +212,7 @@ func Test_GroupMemberCreate(t *testing.T) { }(), }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "dup-at-org", @@ -333,7 +333,7 @@ func Test_GroupMemberDelete(t *testing.T) { found := allocGroupMember() err = rw.LookupWhere(context.Background(), &found, "group_id = ? and member_id = ?", tt.gm.GetGroupId(), tt.gm.GetMemberId()) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/iam/group_test.go b/internal/iam/group_test.go index 615a3cb04..007881672 100644 --- a/internal/iam/group_test.go +++ b/internal/iam/group_test.go @@ -2,12 +2,12 @@ package iam import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/db" dbassert "github.com/hashicorp/boundary/internal/db/assert" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam/store" "github.com/hashicorp/boundary/internal/oplog" "github.com/hashicorp/boundary/internal/types/action" @@ -71,8 +71,8 @@ func TestNewGroup(t *testing.T) { opt: []Option{WithName(id)}, }, wantErr: true, - wantErrMsg: "new group: missing scope id invalid parameter", - wantIsErr: db.ErrInvalidParameter, + wantErrMsg: "new group: missing scope id invalid parameter:", + wantIsErr: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -81,7 +81,7 @@ func TestNewGroup(t *testing.T) { got, err := NewGroup(tt.args.scopePublicId, tt.args.opt...) if tt.wantErr { require.Error(err) - assert.Equal(tt.wantErrMsg, err.Error()) + assert.Contains(err.Error(), tt.wantErrMsg) if tt.wantIsErr != nil { assert.True(errors.Is(err, tt.wantIsErr)) } @@ -341,7 +341,7 @@ func Test_GroupUpdate(t *testing.T) { assert.Equal(tt.wantErrMsg, err.Error()) err = db.TestVerifyOplog(t, rw, grp.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) require.Error(err) - assert.Equal("record not found", err.Error()) + assert.Contains(err.Error(), "record not found") return } require.NoError(err) @@ -427,7 +427,7 @@ func Test_GroupDelete(t *testing.T) { foundGrp.PublicId = tt.group.GetPublicId() err = rw.LookupByPublicId(context.Background(), &foundGrp) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/iam/ids.go b/internal/iam/ids.go index 240c4780b..0b08de525 100644 --- a/internal/iam/ids.go +++ b/internal/iam/ids.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/types/scope" ) @@ -40,7 +41,7 @@ func newGroupId() (string, error) { func newScopeId(scopeType scope.Type) (string, error) { if scopeType == scope.Unknown { - return "", fmt.Errorf("new scope id: unknown is not supported %w", db.ErrInvalidParameter) + return "", fmt.Errorf("new scope id: unknown is not supported %w", errors.ErrInvalidParameter) } id, err := db.NewPublicId(scopeType.Prefix()) if err != nil { diff --git a/internal/iam/ids_test.go b/internal/iam/ids_test.go index 41ead6c5c..287fa38ae 100644 --- a/internal/iam/ids_test.go +++ b/internal/iam/ids_test.go @@ -4,9 +4,7 @@ import ( "strings" "testing" - "errors" - - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/types/scope" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -40,6 +38,6 @@ func Test_PublicIds(t *testing.T) { id, err = newScopeId(scope.Unknown) require.Error(t, err) assert.Empty(t, id) - assert.True(t, errors.Is(err, db.ErrInvalidParameter)) + assert.True(t, errors.Is(err, errors.ErrInvalidParameter)) }) } diff --git a/internal/iam/principal_role.go b/internal/iam/principal_role.go index 19064d262..9bbae767f 100644 --- a/internal/iam/principal_role.go +++ b/internal/iam/principal_role.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam/store" "google.golang.org/protobuf/proto" ) @@ -74,10 +75,10 @@ var _ db.VetForWriter = (*UserRole)(nil) // currently. func NewUserRole(roleId, userId string, opt ...Option) (*UserRole, error) { if roleId == "" { - return nil, fmt.Errorf("new user role: missing role id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new user role: missing role id %w", errors.ErrInvalidParameter) } if userId == "" { - return nil, fmt.Errorf("new user role: missing user id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new user role: missing user id %w", errors.ErrInvalidParameter) } return &UserRole{ UserRole: &store.UserRole{ @@ -104,10 +105,10 @@ func (r *UserRole) Clone() interface{} { // VetForWrite implements db.VetForWrite() interface for user roles. func (role *UserRole) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if role.RoleId == "" { - return fmt.Errorf("new user role: missing role id %w", db.ErrInvalidParameter) + return fmt.Errorf("new user role: missing role id %w", errors.ErrInvalidParameter) } if role.PrincipalId == "" { - return fmt.Errorf("new user role: missing user id %w", db.ErrInvalidParameter) + return fmt.Errorf("new user role: missing user id %w", errors.ErrInvalidParameter) } return nil } @@ -147,10 +148,10 @@ var _ db.VetForWriter = (*GroupRole)(nil) // currently. func NewGroupRole(roleId, groupId string, opt ...Option) (*GroupRole, error) { if roleId == "" { - return nil, fmt.Errorf("new group role: missing role id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new group role: missing role id %w", errors.ErrInvalidParameter) } if groupId == "" { - return nil, fmt.Errorf("new group role: missing group id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new group role: missing group id %w", errors.ErrInvalidParameter) } return &GroupRole{ GroupRole: &store.GroupRole{ @@ -177,10 +178,10 @@ func (r *GroupRole) Clone() interface{} { // VetForWrite implements db.VetForWrite() interface for group roles. func (role *GroupRole) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if role.RoleId == "" { - return fmt.Errorf("new group role: missing role id %w", db.ErrInvalidParameter) + return fmt.Errorf("new group role: missing role id %w", errors.ErrInvalidParameter) } if role.PrincipalId == "" { - return fmt.Errorf("new group role: missing user id %w", db.ErrInvalidParameter) + return fmt.Errorf("new group role: missing user id %w", errors.ErrInvalidParameter) } return nil } diff --git a/internal/iam/principal_role_test.go b/internal/iam/principal_role_test.go index 2b115e5bc..75d50d293 100644 --- a/internal/iam/principal_role_test.go +++ b/internal/iam/principal_role_test.go @@ -2,10 +2,10 @@ package iam import ( "context" - "errors" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam/store" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -68,7 +68,7 @@ func TestNewUserRole(t *testing.T) { }, want: nil, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-user-id", @@ -78,7 +78,7 @@ func TestNewUserRole(t *testing.T) { }, want: nil, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -207,7 +207,7 @@ func TestUserRole_Create(t *testing.T) { }, wantErr: true, wantErrMsg: "create: vet for write failed: new user role: missing role id invalid parameter", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "missing-user-id", @@ -224,7 +224,7 @@ func TestUserRole_Create(t *testing.T) { }, wantErr: true, wantErrMsg: "create: vet for write failed: new user role: missing user id invalid parameter", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "dup-at-org", @@ -345,7 +345,7 @@ func TestUserRole_Delete(t *testing.T) { found := allocUserRole() err = rw.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", tt.role.GetRoleId(), tt.role.GetPrincipalId()) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } @@ -431,7 +431,7 @@ func TestNewGroupRole(t *testing.T) { }, want: nil, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-group-id", @@ -441,7 +441,7 @@ func TestNewGroupRole(t *testing.T) { }, want: nil, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -570,7 +570,7 @@ func TestGroupRole_Create(t *testing.T) { }, wantErr: true, wantErrMsg: "create: vet for write failed: new group role: missing role id invalid parameter", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "missing-user-id", @@ -587,7 +587,7 @@ func TestGroupRole_Create(t *testing.T) { }, wantErr: true, wantErrMsg: "create: vet for write failed: new group role: missing user id invalid parameter", - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "dup-at-org", @@ -728,7 +728,7 @@ func TestGroupRole_Delete(t *testing.T) { found := allocGroupRole() err = rw.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", tt.role.GetRoleId(), tt.role.GetPrincipalId()) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/iam/repository_group.go b/internal/iam/repository_group.go index f4ba0a2a3..cf3603376 100644 --- a/internal/iam/repository_group.go +++ b/internal/iam/repository_group.go @@ -2,12 +2,12 @@ package iam import ( "context" - "errors" "fmt" "strings" "github.com/hashicorp/boundary/internal/db" dbcommon "github.com/hashicorp/boundary/internal/db/common" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" ) @@ -16,16 +16,16 @@ import ( // group. No options are currently supported. func (r *Repository) CreateGroup(ctx context.Context, group *Group, opt ...Option) (*Group, error) { if group == nil { - return nil, fmt.Errorf("create group: missing group %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create group: missing group %w", errors.ErrInvalidParameter) } if group.Group == nil { - return nil, fmt.Errorf("create group: missing group store %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create group: missing group store %w", errors.ErrInvalidParameter) } if group.PublicId != "" { - return nil, fmt.Errorf("create group: public id not empty: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create group: public id not empty: %w", errors.ErrInvalidParameter) } if group.ScopeId == "" { - return nil, fmt.Errorf("create group: missing group scope id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create group: missing group scope id: %w", errors.ErrInvalidParameter) } id, err := newGroupId() if err != nil { @@ -35,8 +35,8 @@ func (r *Repository) CreateGroup(ctx context.Context, group *Group, opt ...Optio g.PublicId = id resource, err := r.create(ctx, g) if err != nil { - if db.IsUniqueError(err) { - return nil, fmt.Errorf("create group: group %s already exists in scope %s: %w", group.Name, group.ScopeId, db.ErrNotUnique) + if errors.IsUniqueError(err) { + return nil, fmt.Errorf("create group: group %s already exists in scope %s: %w", group.Name, group.ScopeId, errors.ErrNotUnique) } return nil, fmt.Errorf("create group: %w for %s", err, g.PublicId) } @@ -50,20 +50,20 @@ func (r *Repository) CreateGroup(ctx context.Context, group *Group, opt ...Optio // If no updatable fields are included in the fieldMaskPaths, then an error is returned. func (r *Repository) UpdateGroup(ctx context.Context, group *Group, version uint32, fieldMaskPaths []string, opt ...Option) (*Group, []*GroupMember, int, error) { if group == nil { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update group: missing group %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update group: missing group %w", errors.ErrInvalidParameter) } if group.Group == nil { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update group: missing group store %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update group: missing group store %w", errors.ErrInvalidParameter) } if group.PublicId == "" { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update group: missing group public id %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update group: missing group public id %w", errors.ErrInvalidParameter) } for _, f := range fieldMaskPaths { switch { case strings.EqualFold("name", f): case strings.EqualFold("description", f): default: - return nil, nil, db.NoRowsAffected, fmt.Errorf("update group: field: %s: %w", f, db.ErrInvalidFieldMask) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update group: field: %s: %w", f, errors.ErrInvalidFieldMask) } } var dbMask, nullFields []string @@ -76,7 +76,7 @@ func (r *Repository) UpdateGroup(ctx context.Context, group *Group, version uint nil, ) if len(dbMask) == 0 && len(nullFields) == 0 { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update group: %w", db.ErrEmptyFieldMask) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update group: %w", errors.ErrEmptyFieldMask) } var resource Resource var rowsUpdated int @@ -104,8 +104,8 @@ func (r *Repository) UpdateGroup(ctx context.Context, group *Group, version uint }, ) if err != nil { - if db.IsUniqueError(err) { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update group: group %s already exists in org %s: %w", group.Name, group.ScopeId, db.ErrNotUnique) + if errors.IsUniqueError(err) { + return nil, nil, db.NoRowsAffected, fmt.Errorf("update group: group %s already exists in org %s: %w", group.Name, group.ScopeId, errors.ErrNotUnique) } return nil, nil, db.NoRowsAffected, fmt.Errorf("update group: %w for %s", err, group.PublicId) } @@ -116,7 +116,7 @@ func (r *Repository) UpdateGroup(ctx context.Context, group *Group, version uint // found, it will return nil, nil. func (r *Repository) LookupGroup(ctx context.Context, withPublicId string, opt ...Option) (*Group, []*GroupMember, error) { if withPublicId == "" { - return nil, nil, fmt.Errorf("lookup group: missing public id %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("lookup group: missing public id %w", errors.ErrInvalidParameter) } g := allocGroup() g.PublicId = withPublicId @@ -141,7 +141,7 @@ func (r *Repository) LookupGroup(ctx context.Context, withPublicId string, opt . }, ) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, nil, nil } return nil, nil, fmt.Errorf("lookup group: failed %w for %s", err, withPublicId) @@ -152,7 +152,7 @@ func (r *Repository) LookupGroup(ctx context.Context, withPublicId string, opt . // DeleteGroup will delete a group from the repository. func (r *Repository) DeleteGroup(ctx context.Context, withPublicId string, opt ...Option) (int, error) { if withPublicId == "" { - return db.NoRowsAffected, fmt.Errorf("delete group: missing public id %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete group: missing public id %w", errors.ErrInvalidParameter) } g := allocGroup() g.PublicId = withPublicId @@ -169,7 +169,7 @@ func (r *Repository) DeleteGroup(ctx context.Context, withPublicId string, opt . // ListGroups in a scope and supports WithLimit option. func (r *Repository) ListGroups(ctx context.Context, withScopeId string, opt ...Option) ([]*Group, error) { if withScopeId == "" { - return nil, fmt.Errorf("list groups: missing scope id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list groups: missing scope id %w", errors.ErrInvalidParameter) } var grps []*Group err := r.list(ctx, &grps, "scope_id = ?", []interface{}{withScopeId}, opt...) @@ -182,7 +182,7 @@ func (r *Repository) ListGroups(ctx context.Context, withScopeId string, opt ... // ListGroupMembers of a group and supports WithLimit option. func (r *Repository) ListGroupMembers(ctx context.Context, withGroupId string, opt ...Option) ([]*GroupMember, error) { if withGroupId == "" { - return nil, fmt.Errorf("list group members: missing group id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list group members: missing group id: %w", errors.ErrInvalidParameter) } members := []*GroupMember{} if err := r.list(ctx, &members, "group_id = ?", []interface{}{withGroupId}, opt...); err != nil { @@ -197,13 +197,13 @@ func (r *Repository) ListGroupMembers(ctx context.Context, withGroupId string, o // and will return an error. func (r *Repository) AddGroupMembers(ctx context.Context, groupId string, groupVersion uint32, userIds []string, opt ...Option) ([]*GroupMember, error) { if groupId == "" { - return nil, fmt.Errorf("add group members: missing group id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("add group members: missing group id %w", errors.ErrInvalidParameter) } if len(userIds) == 0 { - return nil, fmt.Errorf("add group members: missing user ids to add %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("add group members: missing user ids to add %w", errors.ErrInvalidParameter) } if groupVersion == 0 { - return nil, fmt.Errorf("add group members: version cannot be zero: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("add group members: version cannot be zero: %w", errors.ErrInvalidParameter) } group := allocGroup() group.PublicId = groupId @@ -289,13 +289,13 @@ func (r *Repository) AddGroupMembers(ctx context.Context, groupId string, groupV // value for the WithVersion option and will return an error. func (r *Repository) DeleteGroupMembers(ctx context.Context, groupId string, groupVersion uint32, userIds []string, opt ...Option) (int, error) { if groupId == "" { - return db.NoRowsAffected, fmt.Errorf("delete group members: missing group id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete group members: missing group id: %w", errors.ErrInvalidParameter) } if len(userIds) == 0 { - return db.NoRowsAffected, fmt.Errorf("delete group members: missing either user or groups to delete %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete group members: missing either user or groups to delete %w", errors.ErrInvalidParameter) } if groupVersion == 0 { - return db.NoRowsAffected, fmt.Errorf("delete group members: version cannot be zero: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete group members: version cannot be zero: %w", errors.ErrInvalidParameter) } group := allocGroup() group.PublicId = groupId @@ -374,10 +374,10 @@ func (r *Repository) DeleteGroupMembers(ctx context.Context, groupId string, gro // and will return an error. func (r *Repository) SetGroupMembers(ctx context.Context, groupId string, groupVersion uint32, userIds []string, opt ...Option) ([]*GroupMember, int, error) { if groupId == "" { - return nil, db.NoRowsAffected, fmt.Errorf("set group members: missing group id: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("set group members: missing group id: %w", errors.ErrInvalidParameter) } if groupVersion == 0 { - return nil, db.NoRowsAffected, fmt.Errorf("set group members: version cannot be zero: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("set group members: version cannot be zero: %w", errors.ErrInvalidParameter) } group := allocGroup() group.PublicId = groupId diff --git a/internal/iam/repository_group_test.go b/internal/iam/repository_group_test.go index ec3ef98e5..e892fd4a6 100644 --- a/internal/iam/repository_group_test.go +++ b/internal/iam/repository_group_test.go @@ -2,13 +2,13 @@ package iam import ( "context" - "errors" "sort" "testing" "time" "github.com/hashicorp/boundary/internal/db" dbassert "github.com/hashicorp/boundary/internal/db/assert" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/oplog" "github.com/hashicorp/go-uuid" "github.com/stretchr/testify/assert" @@ -71,7 +71,7 @@ func TestRepository_CreateGroup(t *testing.T) { }(), }, wantErrMsg: "create group: public id not empty: invalid parameter", - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, wantErr: true, }, { @@ -81,7 +81,7 @@ func TestRepository_CreateGroup(t *testing.T) { }, wantErr: true, wantErrMsg: "create group: missing group invalid parameter", - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "nil-store", @@ -94,7 +94,7 @@ func TestRepository_CreateGroup(t *testing.T) { }, wantErr: true, wantErrMsg: "create group: missing group store invalid parameter", - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "bad-scope-id", @@ -106,8 +106,8 @@ func TestRepository_CreateGroup(t *testing.T) { }(), }, wantErr: true, - wantErrMsg: "create group: error getting metadata for create: unable to get scope for standard metadata: record not found for", - wantIsError: db.ErrInvalidParameter, + wantErrMsg: "create group: error getting metadata for create: unable to get scope for standard metadata: record not found", + wantIsError: errors.ErrInvalidParameter, }, { name: "dup-name", @@ -122,7 +122,7 @@ func TestRepository_CreateGroup(t *testing.T) { wantDup: true, wantErr: true, wantErrMsg: "already exists in scope ", - wantIsError: db.ErrNotUnique, + wantIsError: errors.ErrNotUnique, }, { name: "dup-name-but-diff-scope", @@ -237,8 +237,8 @@ func TestRepository_UpdateGroup(t *testing.T) { newScopeId: org.PublicId, wantErr: true, wantRowsUpdate: 0, - wantErrMsg: "update group: update: lookup after write: record not found for 1", - wantIsError: db.ErrRecordNotFound, + wantErrMsg: "update group: update: lookup after write: record not found", + wantIsError: errors.ErrRecordNotFound, }, { name: "null-name", @@ -275,7 +275,7 @@ func TestRepository_UpdateGroup(t *testing.T) { wantErr: true, wantRowsUpdate: 0, wantErrMsg: "update group: empty field mask", - wantIsError: db.ErrEmptyFieldMask, + wantIsError: errors.ErrEmptyFieldMask, }, { name: "nil-fieldmask", @@ -288,7 +288,7 @@ func TestRepository_UpdateGroup(t *testing.T) { wantErr: true, wantRowsUpdate: 0, wantErrMsg: "update group: empty field mask", - wantIsError: db.ErrEmptyFieldMask, + wantIsError: errors.ErrEmptyFieldMask, }, { name: "read-only-fields", @@ -301,7 +301,7 @@ func TestRepository_UpdateGroup(t *testing.T) { wantErr: true, wantRowsUpdate: 0, wantErrMsg: "update group: field: CreateTime: invalid field mask", - wantIsError: db.ErrInvalidFieldMask, + wantIsError: errors.ErrInvalidFieldMask, }, { name: "unknown-fields", @@ -314,7 +314,7 @@ func TestRepository_UpdateGroup(t *testing.T) { wantErr: true, wantRowsUpdate: 0, wantErrMsg: "update group: field: Alice: invalid field mask", - wantIsError: db.ErrInvalidFieldMask, + wantIsError: errors.ErrInvalidFieldMask, }, { name: "no-public-id", @@ -327,7 +327,7 @@ func TestRepository_UpdateGroup(t *testing.T) { newScopeId: org.PublicId, wantErr: true, wantErrMsg: "update group: missing group public id invalid parameter", - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, wantRowsUpdate: 0, }, { @@ -339,7 +339,7 @@ func TestRepository_UpdateGroup(t *testing.T) { newScopeId: org.PublicId, wantErr: true, wantErrMsg: "update group: empty field mask", - wantIsError: db.ErrEmptyFieldMask, + wantIsError: errors.ErrEmptyFieldMask, }, { name: "empty-scope-id-with-name-mask", @@ -376,7 +376,7 @@ func TestRepository_UpdateGroup(t *testing.T) { wantErr: true, wantDup: true, wantErrMsg: " already exists in org " + org.PublicId, - wantIsError: db.ErrNotUnique, + wantIsError: errors.ErrNotUnique, }, { name: "modified-scope", @@ -437,7 +437,7 @@ func TestRepository_UpdateGroup(t *testing.T) { assert.Contains(err.Error(), tt.wantErrMsg) err = db.TestVerifyOplog(t, rw, u.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } assert.NoError(err) @@ -519,7 +519,7 @@ func TestRepository_DeleteGroup(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantErrMsg: "delete group: failed record not found for ", + wantErrMsg: "delete group: failed record not found:", }, } for _, tt := range tests { @@ -532,7 +532,7 @@ func TestRepository_DeleteGroup(t *testing.T) { assert.Contains(err.Error(), tt.wantErrMsg) err = db.TestVerifyOplog(t, rw, tt.args.group.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } assert.NoError(err) @@ -727,7 +727,7 @@ func TestRepository_ListMembers(t *testing.T) { got, err := repo.ListGroupMembers(context.Background(), "") require.Error(err) require.Nil(got) - require.Truef(errors.Is(err, db.ErrInvalidParameter), "unexpected error %s", err.Error()) + require.Truef(errors.Is(err, errors.ErrInvalidParameter), "unexpected error %s", err.Error()) }) } @@ -926,7 +926,7 @@ func TestRepository_DeleteGroupMembers(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "bad-version", @@ -949,7 +949,7 @@ func TestRepository_DeleteGroupMembers(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -984,7 +984,7 @@ func TestRepository_DeleteGroupMembers(t *testing.T) { } err = db.TestVerifyOplog(t, rw, tt.args.group.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) diff --git a/internal/iam/repository_principal_role.go b/internal/iam/repository_principal_role.go index e7161e509..b93617a47 100644 --- a/internal/iam/repository_principal_role.go +++ b/internal/iam/repository_principal_role.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" ) @@ -17,17 +18,17 @@ import ( // the WithVersion option and will return an error. func (r *Repository) AddPrincipalRoles(ctx context.Context, roleId string, roleVersion uint32, principalIds []string, opt ...Option) ([]PrincipalRole, error) { if roleId == "" { - return nil, fmt.Errorf("add principal roles: missing role id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("add principal roles: missing role id: %w", errors.ErrInvalidParameter) } if roleVersion == 0 { - return nil, fmt.Errorf("add principal roles: version cannot be zero: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("add principal roles: version cannot be zero: %w", errors.ErrInvalidParameter) } userIds, groupIds, err := splitPrincipals(principalIds) if err != nil { return nil, fmt.Errorf("add principal roles: error parsing principals: %w", err) } if len(userIds) == 0 && len(groupIds) == 0 { - return nil, fmt.Errorf("add principal roles: missing either user or groups to add: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("add principal roles: missing either user or groups to add: %w", errors.ErrInvalidParameter) } newUserRoles := make([]interface{}, 0, len(userIds)) @@ -133,10 +134,10 @@ func (r *Repository) AddPrincipalRoles(ctx context.Context, roleId string, roleV // return an error. func (r *Repository) SetPrincipalRoles(ctx context.Context, roleId string, roleVersion uint32, principalIds []string, opt ...Option) ([]PrincipalRole, int, error) { if roleId == "" { - return nil, db.NoRowsAffected, fmt.Errorf("set principal roles: missing role id: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("set principal roles: missing role id: %w", errors.ErrInvalidParameter) } if roleVersion == 0 { - return nil, db.NoRowsAffected, fmt.Errorf("set principal roles: version cannot be zero: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("set principal roles: version cannot be zero: %w", errors.ErrInvalidParameter) } role := allocRole() role.PublicId = roleId @@ -276,17 +277,17 @@ func (r *Repository) SetPrincipalRoles(ctx context.Context, roleId string, roleV // and will return an error. func (r *Repository) DeletePrincipalRoles(ctx context.Context, roleId string, roleVersion uint32, principalIds []string, opt ...Option) (int, error) { if roleId == "" { - return db.NoRowsAffected, fmt.Errorf("delete principal roles: missing role id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete principal roles: missing role id: %w", errors.ErrInvalidParameter) } userIds, groupIds, err := splitPrincipals(principalIds) if err != nil { return db.NoRowsAffected, fmt.Errorf("remove principal roles: error parsing principals: %w", err) } if len(userIds) == 0 && len(groupIds) == 0 { - return db.NoRowsAffected, fmt.Errorf("delete principal roles: missing either user or groups to delete: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete principal roles: missing either user or groups to delete: %w", errors.ErrInvalidParameter) } if roleVersion == 0 { - return db.NoRowsAffected, fmt.Errorf("delete principal roles: version cannot be zero: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete principal roles: version cannot be zero: %w", errors.ErrInvalidParameter) } role := allocRole() role.PublicId = roleId @@ -385,7 +386,7 @@ func (r *Repository) DeletePrincipalRoles(ctx context.Context, roleId string, ro // ListPrincipalRoles returns the principal roles for the roleId and supports the WithLimit option. func (r *Repository) ListPrincipalRoles(ctx context.Context, roleId string, opt ...Option) ([]PrincipalRole, error) { if roleId == "" { - return nil, fmt.Errorf("lookup principal roles: missing role id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup principal roles: missing role id: %w", errors.ErrInvalidParameter) } var roles []PrincipalRole if err := r.list(ctx, &roles, "role_id = ?", []interface{}{roleId}, opt...); err != nil { @@ -410,7 +411,7 @@ type principalSet struct { func (r *Repository) principalsToSet(ctx context.Context, role *Role, userIds, groupIds []string) (*principalSet, error) { // TODO(mgaffney) 08/2020: Use SQL to calculate changes. if role == nil { - return nil, fmt.Errorf("missing role: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("missing role: %w", errors.ErrInvalidParameter) } existing, err := r.ListPrincipalRoles(ctx, role.PublicId) if err != nil { @@ -497,7 +498,7 @@ func splitPrincipals(principals []string) ([]string, []string, error) { case strings.HasPrefix(principal, GroupPrefix): groups = append(groups, principal) default: - return nil, nil, fmt.Errorf("invalid principal ID %q: %w", principal, db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("invalid principal ID %q: %w", principal, errors.ErrInvalidParameter) } } diff --git a/internal/iam/repository_principal_role_test.go b/internal/iam/repository_principal_role_test.go index 2d5b33656..2add286e4 100644 --- a/internal/iam/repository_principal_role_test.go +++ b/internal/iam/repository_principal_role_test.go @@ -2,12 +2,12 @@ package iam import ( "context" - "errors" "sort" "testing" "time" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/oplog" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -355,7 +355,7 @@ func TestRepository_DeletePrincipalRoles(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "just-user-roles", @@ -402,7 +402,7 @@ func TestRepository_DeletePrincipalRoles(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "zero-version", @@ -416,7 +416,7 @@ func TestRepository_DeletePrincipalRoles(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "bad-version", @@ -499,7 +499,7 @@ func TestRepository_DeletePrincipalRoles(t *testing.T) { } err = db.TestVerifyOplog(t, rw, tt.args.role.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) @@ -772,7 +772,7 @@ func TestRepository_principalsToSet(t *testing.T) { got, err := repo.principalsToSet(context.Background(), nil, users, grps) require.Error(err) assert.Nil(got) - assert.Truef(errors.Is(err, db.ErrInvalidParameter), "unexpected error %s", err.Error()) + assert.Truef(errors.Is(err, errors.ErrInvalidParameter), "unexpected error %s", err.Error()) }) t.Run("no change", func(t *testing.T) { assert, require := assert.New(t), require.New(t) diff --git a/internal/iam/repository_role.go b/internal/iam/repository_role.go index a61e26898..7daf68d85 100644 --- a/internal/iam/repository_role.go +++ b/internal/iam/repository_role.go @@ -2,28 +2,28 @@ package iam import ( "context" - "errors" "fmt" "strings" "github.com/hashicorp/boundary/internal/db" dbcommon "github.com/hashicorp/boundary/internal/db/common" + "github.com/hashicorp/boundary/internal/errors" ) // CreateRole will create a role in the repository and return the written // role. No options are currently supported. func (r *Repository) CreateRole(ctx context.Context, role *Role, opt ...Option) (*Role, error) { if role == nil { - return nil, fmt.Errorf("create role: missing role %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create role: missing role %w", errors.ErrInvalidParameter) } if role.Role == nil { - return nil, fmt.Errorf("create role: missing role store %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create role: missing role store %w", errors.ErrInvalidParameter) } if role.PublicId != "" { - return nil, fmt.Errorf("create role: public id not empty: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create role: public id not empty: %w", errors.ErrInvalidParameter) } if role.ScopeId == "" { - return nil, fmt.Errorf("create role: missing role scope id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create role: missing role scope id: %w", errors.ErrInvalidParameter) } id, err := newRoleId() if err != nil { @@ -33,8 +33,8 @@ func (r *Repository) CreateRole(ctx context.Context, role *Role, opt ...Option) c.PublicId = id resource, err := r.create(ctx, c) if err != nil { - if db.IsUniqueError(err) { - return nil, fmt.Errorf("create role: role %s already exists in scope %s: %w", role.Name, role.ScopeId, db.ErrNotUnique) + if errors.IsUniqueError(err) { + return nil, fmt.Errorf("create role: role %s already exists in scope %s: %w", role.Name, role.ScopeId, errors.ErrNotUnique) } return nil, fmt.Errorf("create role: %w for %s", err, c.PublicId) } @@ -49,13 +49,13 @@ func (r *Repository) CreateRole(ctx context.Context, role *Role, opt ...Option) // then an error is returned. func (r *Repository) UpdateRole(ctx context.Context, role *Role, version uint32, fieldMaskPaths []string, opt ...Option) (*Role, []PrincipalRole, []*RoleGrant, int, error) { if role == nil { - return nil, nil, nil, db.NoRowsAffected, fmt.Errorf("update role: missing role %w", db.ErrInvalidParameter) + return nil, nil, nil, db.NoRowsAffected, fmt.Errorf("update role: missing role %w", errors.ErrInvalidParameter) } if role.Role == nil { - return nil, nil, nil, db.NoRowsAffected, fmt.Errorf("update role: missing role store %w", db.ErrInvalidParameter) + return nil, nil, nil, db.NoRowsAffected, fmt.Errorf("update role: missing role store %w", errors.ErrInvalidParameter) } if role.PublicId == "" { - return nil, nil, nil, db.NoRowsAffected, fmt.Errorf("update role: missing role public id %w", db.ErrInvalidParameter) + return nil, nil, nil, db.NoRowsAffected, fmt.Errorf("update role: missing role public id %w", errors.ErrInvalidParameter) } for _, f := range fieldMaskPaths { switch { @@ -63,7 +63,7 @@ func (r *Repository) UpdateRole(ctx context.Context, role *Role, version uint32, case strings.EqualFold("description", f): case strings.EqualFold("grantscopeid", f): default: - return nil, nil, nil, db.NoRowsAffected, fmt.Errorf("update role: field: %s: %w", f, db.ErrInvalidFieldMask) + return nil, nil, nil, db.NoRowsAffected, fmt.Errorf("update role: field: %s: %w", f, errors.ErrInvalidFieldMask) } } var dbMask, nullFields []string @@ -77,7 +77,7 @@ func (r *Repository) UpdateRole(ctx context.Context, role *Role, version uint32, nil, ) if len(dbMask) == 0 && len(nullFields) == 0 { - return nil, nil, nil, db.NoRowsAffected, fmt.Errorf("update role: %w", db.ErrEmptyFieldMask) + return nil, nil, nil, db.NoRowsAffected, fmt.Errorf("update role: %w", errors.ErrEmptyFieldMask) } var resource Resource var rowsUpdated int @@ -110,8 +110,8 @@ func (r *Repository) UpdateRole(ctx context.Context, role *Role, version uint32, }, ) if err != nil { - if db.IsUniqueError(err) { - return nil, nil, nil, db.NoRowsAffected, fmt.Errorf("update role: role %s already exists in org %s: %w", role.Name, role.ScopeId, db.ErrNotUnique) + if errors.IsUniqueError(err) { + return nil, nil, nil, db.NoRowsAffected, fmt.Errorf("update role: role %s already exists in org %s: %w", role.Name, role.ScopeId, errors.ErrNotUnique) } return nil, nil, nil, db.NoRowsAffected, fmt.Errorf("update role: %w for %s", err, role.PublicId) } @@ -122,7 +122,7 @@ func (r *Repository) UpdateRole(ctx context.Context, role *Role, version uint32, // found, it will return nil, nil. func (r *Repository) LookupRole(ctx context.Context, withPublicId string, opt ...Option) (*Role, []PrincipalRole, []*RoleGrant, error) { if withPublicId == "" { - return nil, nil, nil, fmt.Errorf("lookup role: missing public id %w", db.ErrInvalidParameter) + return nil, nil, nil, fmt.Errorf("lookup role: missing public id %w", errors.ErrInvalidParameter) } role := allocRole() role.PublicId = withPublicId @@ -152,7 +152,7 @@ func (r *Repository) LookupRole(ctx context.Context, withPublicId string, opt .. }, ) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, nil, nil, nil } return nil, nil, nil, err @@ -163,7 +163,7 @@ func (r *Repository) LookupRole(ctx context.Context, withPublicId string, opt .. // DeleteRole will delete a role from the repository. func (r *Repository) DeleteRole(ctx context.Context, withPublicId string, opt ...Option) (int, error) { if withPublicId == "" { - return db.NoRowsAffected, fmt.Errorf("delete role: missing public id %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete role: missing public id %w", errors.ErrInvalidParameter) } role := allocRole() role.PublicId = withPublicId @@ -180,7 +180,7 @@ func (r *Repository) DeleteRole(ctx context.Context, withPublicId string, opt .. // ListRoles in a scope and supports WithLimit option. func (r *Repository) ListRoles(ctx context.Context, withScopeId string, opt ...Option) ([]*Role, error) { if withScopeId == "" { - return nil, fmt.Errorf("list roles: missing scope id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list roles: missing scope id %w", errors.ErrInvalidParameter) } var roles []*Role err := r.list(ctx, &roles, "scope_id = ?", []interface{}{withScopeId}, opt...) diff --git a/internal/iam/repository_role_grant.go b/internal/iam/repository_role_grant.go index 21221bc28..5fc1fff66 100644 --- a/internal/iam/repository_role_grant.go +++ b/internal/iam/repository_role_grant.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" "github.com/hashicorp/boundary/internal/perms" @@ -15,13 +16,13 @@ import ( // the WithVersion option and will return an error. func (r *Repository) AddRoleGrants(ctx context.Context, roleId string, roleVersion uint32, grants []string, opt ...Option) ([]*RoleGrant, error) { if roleId == "" { - return nil, fmt.Errorf("add role grants: missing role id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("add role grants: missing role id %w", errors.ErrInvalidParameter) } if len(grants) == 0 { - return nil, fmt.Errorf("add role grants: missing grants: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("add role grants: missing grants: %w", errors.ErrInvalidParameter) } if roleVersion == 0 { - return nil, fmt.Errorf("add role grants: version cannot be zero: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("add role grants: version cannot be zero: %w", errors.ErrInvalidParameter) } role := allocRole() role.PublicId = roleId @@ -103,13 +104,13 @@ func (r *Repository) AddRoleGrants(ctx context.Context, roleId string, roleVersi // error. func (r *Repository) DeleteRoleGrants(ctx context.Context, roleId string, roleVersion uint32, grants []string, opt ...Option) (int, error) { if roleId == "" { - return 0, fmt.Errorf("delete role grants: missing role id %w", db.ErrInvalidParameter) + return 0, fmt.Errorf("delete role grants: missing role id %w", errors.ErrInvalidParameter) } if len(grants) == 0 { - return 0, fmt.Errorf("delete role grants: missing grants: %w", db.ErrInvalidParameter) + return 0, fmt.Errorf("delete role grants: missing grants: %w", errors.ErrInvalidParameter) } if roleVersion == 0 { - return 0, fmt.Errorf("delete role grants: version cannot be zero: %w", db.ErrInvalidParameter) + return 0, fmt.Errorf("delete role grants: version cannot be zero: %w", errors.ErrInvalidParameter) } role := allocRole() role.PublicId = roleId @@ -217,15 +218,15 @@ func (r *Repository) DeleteRoleGrants(ctx context.Context, roleId string, roleVe // value for the WithVersion option and will return an error. func (r *Repository) SetRoleGrants(ctx context.Context, roleId string, roleVersion uint32, grants []string, opt ...Option) ([]*RoleGrant, int, error) { if roleId == "" { - return nil, db.NoRowsAffected, fmt.Errorf("set role grants: missing role id %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("set role grants: missing role id %w", errors.ErrInvalidParameter) } if roleVersion == 0 { - return nil, db.NoRowsAffected, fmt.Errorf("set role grants: version cannot be zero: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("set role grants: version cannot be zero: %w", errors.ErrInvalidParameter) } // Explicitly set to zero clears, but treat nil as a mistake if grants == nil { - return nil, db.NoRowsAffected, fmt.Errorf("set role grants: nil grants: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("set role grants: nil grants: %w", errors.ErrInvalidParameter) } role := allocRole() @@ -371,7 +372,7 @@ func (r *Repository) SetRoleGrants(ctx context.Context, roleId string, roleVersi // option. func (r *Repository) ListRoleGrants(ctx context.Context, roleId string, opt ...Option) ([]*RoleGrant, error) { if roleId == "" { - return nil, fmt.Errorf("add role grants: missing role id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("add role grants: missing role id %w", errors.ErrInvalidParameter) } var roleGrants []*RoleGrant if err := r.list(ctx, &roleGrants, "role_id = ?", []interface{}{roleId}, opt...); err != nil { @@ -382,7 +383,7 @@ func (r *Repository) ListRoleGrants(ctx context.Context, roleId string, opt ...O func (r *Repository) GrantsForUser(ctx context.Context, userId string, opt ...Option) ([]perms.GrantPair, error) { if userId == "" { - return nil, fmt.Errorf("get grants for user: missing user id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("get grants for user: missing user id: %w", errors.ErrInvalidParameter) } const ( diff --git a/internal/iam/repository_role_grant_test.go b/internal/iam/repository_role_grant_test.go index 33a6f7608..495f631ca 100644 --- a/internal/iam/repository_role_grant_test.go +++ b/internal/iam/repository_role_grant_test.go @@ -2,13 +2,13 @@ package iam import ( "context" - "errors" "fmt" "math/rand" "testing" "time" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/oplog" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -271,7 +271,7 @@ func TestRepository_DeleteRoleGrants(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { @@ -295,7 +295,7 @@ func TestRepository_DeleteRoleGrants(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "invalid-grant-strings", @@ -380,7 +380,7 @@ func TestRepository_DeleteRoleGrants(t *testing.T) { } err = db.TestVerifyOplog(t, rw, tt.args.role.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) diff --git a/internal/iam/repository_role_test.go b/internal/iam/repository_role_test.go index d92b45bb6..14f957b6f 100644 --- a/internal/iam/repository_role_test.go +++ b/internal/iam/repository_role_test.go @@ -2,13 +2,13 @@ package iam import ( "context" - "errors" "fmt" "testing" "time" "github.com/hashicorp/boundary/internal/db" dbassert "github.com/hashicorp/boundary/internal/db/assert" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam/store" "github.com/hashicorp/boundary/internal/oplog" "github.com/hashicorp/go-uuid" @@ -72,7 +72,7 @@ func TestRepository_CreateRole(t *testing.T) { }(), }, wantErrMsg: "create role: public id not empty: invalid parameter", - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, wantErr: true, }, { @@ -82,7 +82,7 @@ func TestRepository_CreateRole(t *testing.T) { }, wantErr: true, wantErrMsg: "create role: missing role invalid parameter", - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "nil-store", @@ -95,7 +95,7 @@ func TestRepository_CreateRole(t *testing.T) { }, wantErr: true, wantErrMsg: "create role: missing role store invalid parameter", - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "bad-scope-id", @@ -107,8 +107,8 @@ func TestRepository_CreateRole(t *testing.T) { }(), }, wantErr: true, - wantErrMsg: "create role: error getting metadata for create: unable to get scope for standard metadata: record not found for", - wantIsError: db.ErrInvalidParameter, + wantErrMsg: "create role: error getting metadata for create: unable to get scope for standard metadata: record not found:", + wantIsError: errors.ErrInvalidParameter, }, { name: "dup-name", @@ -123,7 +123,7 @@ func TestRepository_CreateRole(t *testing.T) { wantDup: true, wantErr: true, wantErrMsg: "already exists in scope ", - wantIsError: db.ErrNotUnique, + wantIsError: errors.ErrNotUnique, }, { name: "dup-name-but-diff-scope", @@ -238,8 +238,8 @@ func TestRepository_UpdateRole(t *testing.T) { newScopeId: org.PublicId, wantErr: true, wantRowsUpdate: 0, - wantErrMsg: "update role: update: lookup after write: record not found for 1", - wantIsError: db.ErrRecordNotFound, + wantErrMsg: "update role: update: lookup after write: record not found:", + wantIsError: errors.ErrRecordNotFound, }, { name: "null-name", @@ -276,7 +276,7 @@ func TestRepository_UpdateRole(t *testing.T) { wantErr: true, wantRowsUpdate: 0, wantErrMsg: "update role: empty field mask", - wantIsError: db.ErrEmptyFieldMask, + wantIsError: errors.ErrEmptyFieldMask, }, { name: "nil-fieldmask", @@ -289,7 +289,7 @@ func TestRepository_UpdateRole(t *testing.T) { wantErr: true, wantRowsUpdate: 0, wantErrMsg: "update role: empty field mask", - wantIsError: db.ErrEmptyFieldMask, + wantIsError: errors.ErrEmptyFieldMask, }, { name: "read-only-fields", @@ -302,7 +302,7 @@ func TestRepository_UpdateRole(t *testing.T) { wantErr: true, wantRowsUpdate: 0, wantErrMsg: "update role: field: CreateTime: invalid field mask", - wantIsError: db.ErrInvalidFieldMask, + wantIsError: errors.ErrInvalidFieldMask, }, { name: "unknown-fields", @@ -315,7 +315,7 @@ func TestRepository_UpdateRole(t *testing.T) { wantErr: true, wantRowsUpdate: 0, wantErrMsg: "update role: field: Alice: invalid field mask", - wantIsError: db.ErrInvalidFieldMask, + wantIsError: errors.ErrInvalidFieldMask, }, { name: "no-public-id", @@ -328,7 +328,7 @@ func TestRepository_UpdateRole(t *testing.T) { newScopeId: org.PublicId, wantErr: true, wantErrMsg: "update role: missing role public id invalid parameter", - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, wantRowsUpdate: 0, }, { @@ -340,7 +340,7 @@ func TestRepository_UpdateRole(t *testing.T) { newScopeId: org.PublicId, wantErr: true, wantErrMsg: "update role: empty field mask", - wantIsError: db.ErrEmptyFieldMask, + wantIsError: errors.ErrEmptyFieldMask, }, { name: "empty-scope-id-with-name-mask", @@ -377,7 +377,7 @@ func TestRepository_UpdateRole(t *testing.T) { wantErr: true, wantDup: true, wantErrMsg: " already exists in org " + org.PublicId, - wantIsError: db.ErrNotUnique, + wantIsError: errors.ErrNotUnique, }, } for _, tt := range tests { @@ -431,7 +431,7 @@ func TestRepository_UpdateRole(t *testing.T) { assert.Contains(err.Error(), tt.wantErrMsg) err = db.TestVerifyOplog(t, rw, r.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) @@ -517,7 +517,7 @@ func TestRepository_DeleteRole(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantErrMsg: "delete role: failed record not found for ", + wantErrMsg: "delete role: failed record not found:", }, } for _, tt := range tests { @@ -530,7 +530,7 @@ func TestRepository_DeleteRole(t *testing.T) { assert.Contains(err.Error(), tt.wantErrMsg) err = db.TestVerifyOplog(t, rw, tt.args.role.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } assert.NoError(err) diff --git a/internal/iam/repository_scope.go b/internal/iam/repository_scope.go index 1cacc157a..64d96e506 100644 --- a/internal/iam/repository_scope.go +++ b/internal/iam/repository_scope.go @@ -3,12 +3,12 @@ package iam import ( "context" "crypto/rand" - "errors" "fmt" "strings" "github.com/hashicorp/boundary/internal/db" dbcommon "github.com/hashicorp/boundary/internal/db/common" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" "github.com/hashicorp/boundary/internal/types/resource" @@ -20,13 +20,13 @@ import ( // scope. Supported options include: WithPublicId and WithRandomReader. func (r *Repository) CreateScope(ctx context.Context, s *Scope, userId string, opt ...Option) (*Scope, error) { if s == nil { - return nil, fmt.Errorf("create scope: missing scope %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create scope: missing scope %w", errors.ErrInvalidParameter) } if s.Scope == nil { - return nil, fmt.Errorf("create scope: missing scope store %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create scope: missing scope store %w", errors.ErrInvalidParameter) } if s.PublicId != "" { - return nil, fmt.Errorf("create scope: public id not empty: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create scope: public id not empty: %w", errors.ErrInvalidParameter) } var parentOplogWrapper wrapping.Wrapper @@ -34,13 +34,13 @@ func (r *Repository) CreateScope(ctx context.Context, s *Scope, userId string, o var err error switch s.Type { case scope.Unknown.String(): - return nil, fmt.Errorf("create scope: unknown type: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create scope: unknown type: %w", errors.ErrInvalidParameter) case scope.Global.String(): - return nil, fmt.Errorf("create scope: invalid type: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create scope: invalid type: %w", errors.ErrInvalidParameter) default: switch s.ParentId { case "": - return nil, fmt.Errorf("create scope: missing parent id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create scope: missing parent id: %w", errors.ErrInvalidParameter) case scope.Global.String(): parentOplogWrapper, err = r.kms.GetWrapper(ctx, scope.Global.String(), kms.KeyPurposeOplog) default: @@ -335,8 +335,8 @@ func (r *Repository) CreateScope(ctx context.Context, s *Scope, userId string, o ) if err != nil { - if db.IsUniqueError(err) { - return nil, fmt.Errorf("create scope: scope %s/%s already exists: %w", scopePublicId, s.Name, db.ErrNotUnique) + if errors.IsUniqueError(err) { + return nil, fmt.Errorf("create scope: scope %s/%s already exists: %w", scopePublicId, s.Name, errors.ErrNotUnique) } return nil, fmt.Errorf("create scope: id %s got error: %w", scopePublicId, err) } @@ -351,13 +351,13 @@ func (r *Repository) CreateScope(ctx context.Context, s *Scope, userId string, o // fieldMaskPaths, then an error is returned. func (r *Repository) UpdateScope(ctx context.Context, scope *Scope, version uint32, fieldMaskPaths []string, opt ...Option) (*Scope, int, error) { if scope == nil { - return nil, db.NoRowsAffected, fmt.Errorf("update scope: missing scope: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update scope: missing scope: %w", errors.ErrInvalidParameter) } if scope.PublicId == "" { - return nil, db.NoRowsAffected, fmt.Errorf("update scope: missing public id: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("update scope: missing public id: %w", errors.ErrInvalidParameter) } if contains(fieldMaskPaths, "ParentId") { - return nil, db.NoRowsAffected, fmt.Errorf("update scope: you cannot change a scope's parent: %w", db.ErrInvalidFieldMask) + return nil, db.NoRowsAffected, fmt.Errorf("update scope: you cannot change a scope's parent: %w", errors.ErrInvalidFieldMask) } var dbMask, nullFields []string dbMask, nullFields = dbcommon.BuildUpdatePaths( @@ -370,13 +370,13 @@ func (r *Repository) UpdateScope(ctx context.Context, scope *Scope, version uint ) // nada to update, so reload scope from db and return it if len(dbMask) == 0 && len(nullFields) == 0 { - return nil, db.NoRowsAffected, fmt.Errorf("update scope: %w", db.ErrEmptyFieldMask) + return nil, db.NoRowsAffected, fmt.Errorf("update scope: %w", errors.ErrEmptyFieldMask) } resource, rowsUpdated, err := r.update(ctx, scope, version, dbMask, nullFields) if err != nil { - if db.IsUniqueError(err) { - return nil, db.NoRowsAffected, fmt.Errorf("update scope: %s name %s already exists: %w", scope.PublicId, scope.Name, db.ErrNotUnique) + if errors.IsUniqueError(err) { + return nil, db.NoRowsAffected, fmt.Errorf("update scope: %s name %s already exists: %w", scope.PublicId, scope.Name, errors.ErrNotUnique) } return nil, db.NoRowsAffected, fmt.Errorf("update scope: failed for public id %s: %w", scope.PublicId, err) } @@ -387,12 +387,12 @@ func (r *Repository) UpdateScope(ctx context.Context, scope *Scope, version uint // found, it will return nil, nil. func (r *Repository) LookupScope(ctx context.Context, withPublicId string, opt ...Option) (*Scope, error) { if withPublicId == "" { - return nil, fmt.Errorf("lookup scope: missing public id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup scope: missing public id %w", errors.ErrInvalidParameter) } scope := allocScope() scope.PublicId = withPublicId if err := r.reader.LookupByPublicId(ctx, &scope); err != nil { - if err == db.ErrRecordNotFound { + if err == errors.ErrRecordNotFound { return nil, nil } return nil, fmt.Errorf("lookup scope: failed %w fo %s", err, withPublicId) @@ -403,10 +403,10 @@ func (r *Repository) LookupScope(ctx context.Context, withPublicId string, opt . // DeleteScope will delete a scope from the repository func (r *Repository) DeleteScope(ctx context.Context, withPublicId string, opt ...Option) (int, error) { if withPublicId == "" { - return db.NoRowsAffected, fmt.Errorf("delete scope: missing public id %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete scope: missing public id %w", errors.ErrInvalidParameter) } if withPublicId == scope.Global.String() { - return db.NoRowsAffected, fmt.Errorf("delete scope: invalid to delete global scope: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete scope: invalid to delete global scope: %w", errors.ErrInvalidParameter) } scope := allocScope() scope.PublicId = withPublicId @@ -423,7 +423,7 @@ func (r *Repository) DeleteScope(ctx context.Context, withPublicId string, opt . // ListProjects in an org and supports the WithLimit option. func (r *Repository) ListProjects(ctx context.Context, withOrgId string, opt ...Option) ([]*Scope, error) { if withOrgId == "" { - return nil, fmt.Errorf("list projects: missing org id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list projects: missing org id %w", errors.ErrInvalidParameter) } var projects []*Scope err := r.list(ctx, &projects, "parent_id = ? and type = ?", []interface{}{withOrgId, scope.Project.String()}, opt...) diff --git a/internal/iam/repository_scope_test.go b/internal/iam/repository_scope_test.go index 19339ddb1..6af72f43c 100644 --- a/internal/iam/repository_scope_test.go +++ b/internal/iam/repository_scope_test.go @@ -197,7 +197,7 @@ func Test_Repository_Scope_Update(t *testing.T) { require.Error(err) assert.Nil(project) assert.Equal(0, updatedRows) - assert.Equal("update scope: you cannot change a scope's parent: invalid field mask", err.Error()) + assert.Contains(err.Error(), "update scope: you cannot change a scope's parent: invalid field mask") }) } @@ -433,7 +433,7 @@ func TestRepository_UpdateScope(t *testing.T) { if tt.wantErr { require.Error(err) assert.Equal(tt.wantUpdatedRows, rowsUpdated) - assert.Equal(tt.wantErrMsg, err.Error()) + assert.Contains(err.Error(), tt.wantErrMsg) return } require.NoError(err) diff --git a/internal/iam/repository_user.go b/internal/iam/repository_user.go index 93445ab2f..b91f59399 100644 --- a/internal/iam/repository_user.go +++ b/internal/iam/repository_user.go @@ -2,12 +2,13 @@ package iam import ( "context" - "errors" + stdErrors "errors" "fmt" "strings" "github.com/hashicorp/boundary/internal/db" dbcommon "github.com/hashicorp/boundary/internal/db/common" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" "github.com/hashicorp/boundary/internal/types/scope" @@ -16,10 +17,10 @@ import ( // CreateUser will create a user in the repository and return the written user func (r *Repository) CreateUser(ctx context.Context, user *User, opt ...Option) (*User, error) { if user == nil { - return nil, fmt.Errorf("create user: missing user %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create user: missing user %w", errors.ErrInvalidParameter) } if user.PublicId != "" { - return nil, fmt.Errorf("create user: public id is not empty %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create user: public id is not empty %w", errors.ErrInvalidParameter) } u := user.Clone().(*User) @@ -27,7 +28,7 @@ func (r *Repository) CreateUser(ctx context.Context, user *User, opt ...Option) if opts.withPublicId != "" { if !strings.HasPrefix(opts.withPublicId, UserPrefix+"_") { - return nil, fmt.Errorf("create user: passed-in public ID %q has wrong prefix, should be %q: %w", opts.withPublicId, UserPrefix, db.ErrInvalidPublicId) + return nil, fmt.Errorf("create user: passed-in public ID %q has wrong prefix, should be %q: %w", opts.withPublicId, UserPrefix, errors.ErrInvalidPublicId) } u.PublicId = opts.withPublicId } else { @@ -40,7 +41,7 @@ func (r *Repository) CreateUser(ctx context.Context, user *User, opt ...Option) resource, err := r.create(ctx, u) if err != nil { - if db.IsUniqueError(err) { + if errors.IsUniqueError(err) { return nil, fmt.Errorf("create user: user %s already exists in org %s: %w", user.Name, user.ScopeId, err) } return nil, fmt.Errorf("create user: %w for %s", err, u.PublicId) @@ -56,17 +57,17 @@ func (r *Repository) CreateUser(ctx context.Context, user *User, opt ...Option) // fieldMaskPaths, then an error is returned. func (r *Repository) UpdateUser(ctx context.Context, user *User, version uint32, fieldMaskPaths []string, opt ...Option) (*User, []string, int, error) { if user == nil { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update user: missing user %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update user: missing user %w", errors.ErrInvalidParameter) } if user.PublicId == "" { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update user: missing user public id %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update user: missing user public id %w", errors.ErrInvalidParameter) } for _, f := range fieldMaskPaths { switch { case strings.EqualFold("name", f): case strings.EqualFold("description", f): default: - return nil, nil, db.NoRowsAffected, fmt.Errorf("update user: field: %s: %w", f, db.ErrInvalidFieldMask) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update user: field: %s: %w", f, errors.ErrInvalidFieldMask) } } var dbMask, nullFields []string @@ -79,7 +80,7 @@ func (r *Repository) UpdateUser(ctx context.Context, user *User, version uint32, nil, ) if len(dbMask) == 0 && len(nullFields) == 0 { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update user: %w", db.ErrEmptyFieldMask) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update user: %w", errors.ErrEmptyFieldMask) } u := user.Clone().(*User) @@ -126,7 +127,7 @@ func (r *Repository) UpdateUser(ctx context.Context, user *User, version uint32, ) if err == nil && rowsUpdated > 1 { // return err, which will result in a rollback of the update - return errors.New("error more than 1 resource would have been updated ") + return stdErrors.New("error more than 1 resource would have been updated ") } if err != nil { return err @@ -147,7 +148,7 @@ func (r *Repository) UpdateUser(ctx context.Context, user *User, version uint32, }, ) if err != nil { - if db.IsUniqueError(err) { + if errors.IsUniqueError(err) { return nil, nil, db.NoRowsAffected, fmt.Errorf("update user: user %s already exists in org %s", user.Name, user.ScopeId) } return nil, nil, db.NoRowsAffected, fmt.Errorf("update user: %w for %s", err, user.PublicId) @@ -159,13 +160,13 @@ func (r *Repository) UpdateUser(ctx context.Context, user *User, version uint32, // repository. If the user is not found, it will return nil, nil, nil. func (r *Repository) LookupUser(ctx context.Context, userId string, opt ...Option) (*User, []string, error) { if userId == "" { - return nil, nil, fmt.Errorf("lookup user: missing public id %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("lookup user: missing public id %w", errors.ErrInvalidParameter) } user := allocUser() user.PublicId = userId if err := r.reader.LookupByPublicId(ctx, &user); err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, nil, nil } return nil, nil, fmt.Errorf("lookup user: failed %w for %s", err, userId) @@ -180,7 +181,7 @@ func (r *Repository) LookupUser(ctx context.Context, userId string, opt ...Optio // DeleteUser will delete a user from the repository func (r *Repository) DeleteUser(ctx context.Context, withPublicId string, opt ...Option) (int, error) { if withPublicId == "" { - return db.NoRowsAffected, fmt.Errorf("delete user: missing public id %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete user: missing public id %w", errors.ErrInvalidParameter) } user := allocUser() user.PublicId = withPublicId @@ -197,7 +198,7 @@ func (r *Repository) DeleteUser(ctx context.Context, withPublicId string, opt .. // ListUsers in an org and supports the WithLimit option. func (r *Repository) ListUsers(ctx context.Context, withOrgId string, opt ...Option) ([]*User, error) { if withOrgId == "" { - return nil, fmt.Errorf("list users: missing org id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list users: missing org id %w", errors.ErrInvalidParameter) } var users []*User err := r.list(ctx, &users, "scope_id = ?", []interface{}{withOrgId}, opt...) @@ -216,7 +217,7 @@ func (r *Repository) ListUsers(ctx context.Context, withOrgId string, opt ...Opt func (r *Repository) LookupUserWithLogin(ctx context.Context, accountId string, opt ...Option) (*User, error) { opts := getOpts(opt...) if accountId == "" { - return nil, fmt.Errorf("lookup user with login: missing account id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup user with login: missing account id %w", errors.ErrInvalidParameter) } u, err := r.getUserWithAccount(ctx, accountId) if err != nil { @@ -226,7 +227,7 @@ func (r *Repository) LookupUserWithLogin(ctx context.Context, accountId string, return u, nil } if !opts.withAutoVivify { - return nil, fmt.Errorf("lookup user with login: user not found for account %s: %w", accountId, db.ErrRecordNotFound) + return nil, fmt.Errorf("lookup user with login: user not found for account %s: %w", accountId, errors.ErrRecordNotFound) } acct := allocAccount() @@ -302,7 +303,7 @@ func (r *Repository) LookupUserWithLogin(ctx context.Context, accountId string, func (r *Repository) getUserWithAccount(ctx context.Context, withAccountId string, opt ...Option) (*User, error) { if withAccountId == "" { - return nil, fmt.Errorf("missing account id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("missing account id %w", errors.ErrInvalidParameter) } rows, err := r.reader.Query(ctx, whereUserAccount, []interface{}{withAccountId}) if err != nil { @@ -331,7 +332,7 @@ func (r *Repository) getUserWithAccount(ctx context.Context, withAccountId strin // WithLimit option. Returns nil, nil when no associated accounts are found. func (r *Repository) ListUserAccounts(ctx context.Context, userId string, opt ...Option) ([]string, error) { if userId == "" { - return nil, fmt.Errorf("list auth account ids: missing user id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list auth account ids: missing user id: %w", errors.ErrInvalidParameter) } var accounts []*authAccount if err := r.list(ctx, &accounts, "iam_user_id = ?", []interface{}{userId}, opt...); err != nil { @@ -353,13 +354,13 @@ func (r *Repository) ListUserAccounts(ctx context.Context, userId string, opt .. // supported. func (r *Repository) AddUserAccounts(ctx context.Context, userId string, userVersion uint32, accountIds []string, opt ...Option) ([]string, error) { if userId == "" { - return nil, fmt.Errorf("associate accounts: missing user public id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("associate accounts: missing user public id %w", errors.ErrInvalidParameter) } if userVersion == 0 { - return nil, fmt.Errorf("associate accounts: missing user version %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("associate accounts: missing user version %w", errors.ErrInvalidParameter) } if len(accountIds) == 0 { - return nil, fmt.Errorf("associate accounts: missing account id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("associate accounts: missing account id %w", errors.ErrInvalidParameter) } user := allocUser() @@ -434,13 +435,13 @@ func (r *Repository) AddUserAccounts(ctx context.Context, userId string, userVer // supported. func (r *Repository) DeleteUserAccounts(ctx context.Context, userId string, userVersion uint32, accountIds []string, opt ...Option) ([]string, error) { if userId == "" { - return nil, fmt.Errorf("disassociate accounts: missing user public id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("disassociate accounts: missing user public id %w", errors.ErrInvalidParameter) } if userVersion == 0 { - return nil, fmt.Errorf("disassociate accounts: missing user version %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("disassociate accounts: missing user version %w", errors.ErrInvalidParameter) } if len(accountIds) == 0 { - return nil, fmt.Errorf("disassociate accounts: missing account id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("disassociate accounts: missing account id %w", errors.ErrInvalidParameter) } user := allocUser() @@ -514,10 +515,10 @@ func (r *Repository) DeleteUserAccounts(ctx context.Context, userId string, user // supported. func (r *Repository) SetUserAccounts(ctx context.Context, userId string, userVersion uint32, accountIds []string, opt ...Option) ([]string, error) { if userId == "" { - return nil, fmt.Errorf("set associated accounts: missing user public id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("set associated accounts: missing user public id %w", errors.ErrInvalidParameter) } if userVersion == 0 { - return nil, fmt.Errorf("set associated accounts: missing user version %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("set associated accounts: missing user version %w", errors.ErrInvalidParameter) } user := allocUser() @@ -619,19 +620,19 @@ func (r *Repository) SetUserAccounts(ctx context.Context, userId string, userVer // the user (userId) within the writer's database func associateUserWithAccounts(ctx context.Context, repoKms *kms.Kms, reader db.Reader, writer db.Writer, userId string, accountIds []string, opt ...Option) error { if repoKms == nil { - return fmt.Errorf("associate user with accounts: kms is nil: %w", db.ErrInvalidParameter) + return fmt.Errorf("associate user with accounts: kms is nil: %w", errors.ErrInvalidParameter) } if reader == nil { - return fmt.Errorf("associate user with accounts: db reader is nil: %w", db.ErrInvalidParameter) + return fmt.Errorf("associate user with accounts: db reader is nil: %w", errors.ErrInvalidParameter) } if writer == nil { - return fmt.Errorf("associate user with accounts: db writer is nil: %w", db.ErrInvalidParameter) + return fmt.Errorf("associate user with accounts: db writer is nil: %w", errors.ErrInvalidParameter) } if userId == "" { - return fmt.Errorf("associate user with accounts: user id is empty: %w", db.ErrInvalidParameter) + return fmt.Errorf("associate user with accounts: user id is empty: %w", errors.ErrInvalidParameter) } if len(accountIds) == 0 { - return fmt.Errorf("associate user with accounts: missing account id %w", db.ErrInvalidParameter) + return fmt.Errorf("associate user with accounts: missing account id %w", errors.ErrInvalidParameter) } authAccounts := make([]*authAccount, 0, len(accountIds)) for _, accountId := range accountIds { @@ -642,7 +643,7 @@ func associateUserWithAccounts(ctx context.Context, repoKms *kms.Kms, reader db. return fmt.Errorf("associate user with accounts: unable to lookup account %s: %w", accountId, err) } if acct.IamUserId != "" && acct.IamUserId != userId { - return fmt.Errorf("associate user with accounts: %s account is associated with a user %s: %w", accountId, acct.IamUserId, db.ErrInvalidParameter) + return fmt.Errorf("associate user with accounts: %s account is associated with a user %s: %w", accountId, acct.IamUserId, errors.ErrInvalidParameter) } authAccounts = append(authAccounts, &acct) } @@ -682,19 +683,19 @@ func associateUserWithAccounts(ctx context.Context, repoKms *kms.Kms, reader db. // user. No options are currently supported. func dissociateUserFromAccounts(ctx context.Context, repoKms *kms.Kms, reader db.Reader, writer db.Writer, userId string, accountIds []string, opt ...Option) error { if repoKms == nil { - return fmt.Errorf("dissociate user from accounts: kms is nil: %w", db.ErrInvalidParameter) + return fmt.Errorf("dissociate user from accounts: kms is nil: %w", errors.ErrInvalidParameter) } if reader == nil { - return fmt.Errorf("dissociate user from accounts: db reader is nil: %w", db.ErrInvalidParameter) + return fmt.Errorf("dissociate user from accounts: db reader is nil: %w", errors.ErrInvalidParameter) } if writer == nil { - return fmt.Errorf("dissociate user from accounts: db writer is nil: %w", db.ErrInvalidParameter) + return fmt.Errorf("dissociate user from accounts: db writer is nil: %w", errors.ErrInvalidParameter) } if userId == "" { - return fmt.Errorf("dissociate user from accounts: missing user public id %w", db.ErrInvalidParameter) + return fmt.Errorf("dissociate user from accounts: missing user public id %w", errors.ErrInvalidParameter) } if len(accountIds) == 0 { - return fmt.Errorf("dissociate user from accounts: missing account id %w", db.ErrInvalidParameter) + return fmt.Errorf("dissociate user from accounts: missing account id %w", errors.ErrInvalidParameter) } authAccounts := make([]*authAccount, 0, len(accountIds)) for _, accountId := range accountIds { @@ -705,7 +706,7 @@ func dissociateUserFromAccounts(ctx context.Context, repoKms *kms.Kms, reader db return fmt.Errorf("dissociate user from accounts: unable to lookup account %s: %w", accountId, err) } if acct.IamUserId != userId { - return fmt.Errorf("dissociate user from accounts: %s account is not associated with user %s: %w", accountId, userId, db.ErrInvalidParameter) + return fmt.Errorf("dissociate user from accounts: %s account is not associated with user %s: %w", accountId, userId, errors.ErrInvalidParameter) } authAccounts = append(authAccounts, &acct) } diff --git a/internal/iam/repository_user_test.go b/internal/iam/repository_user_test.go index 64987acfa..73bd60c3b 100644 --- a/internal/iam/repository_user_test.go +++ b/internal/iam/repository_user_test.go @@ -2,15 +2,14 @@ package iam import ( "context" - "errors" "fmt" "sort" - "strings" "testing" "time" "github.com/hashicorp/boundary/internal/db" dbassert "github.com/hashicorp/boundary/internal/db/assert" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" "github.com/hashicorp/boundary/sdk/strutil" @@ -60,7 +59,7 @@ func TestRepository_CreateUser(t *testing.T) { }(), }, wantErr: true, - wantErrMsg: "create user: error getting metadata for create: unable to get scope for standard metadata: record not found for", + wantErrMsg: "create user: error getting metadata for create: unable to get scope for standard metadata: record not found:", }, { name: "dup-name", @@ -92,7 +91,7 @@ func TestRepository_CreateUser(t *testing.T) { case "dup-name": assert.Contains(err.Error(), fmt.Sprintf(tt.wantErrMsg, "dup-name"+id, org.PublicId)) default: - assert.True(strings.HasPrefix(err.Error(), tt.wantErrMsg)) + assert.Contains(err.Error(), tt.wantErrMsg) } return } @@ -171,8 +170,8 @@ func TestRepository_UpdateUser(t *testing.T) { }, wantErr: true, wantRowsUpdate: 0, - wantErrMsg: "update user: update: lookup after write: record not found for 1", - wantIsErr: db.ErrRecordNotFound, + wantErrMsg: "update user: update: lookup after write: record not found:", + wantIsErr: errors.ErrRecordNotFound, }, { name: "null-name", @@ -341,7 +340,7 @@ func TestRepository_UpdateUser(t *testing.T) { if tt.wantErr { require.Error(err) if tt.wantIsErr != nil { - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) } assert.Nil(userAfterUpdate) assert.Equal(0, updatedRows) @@ -353,7 +352,7 @@ func TestRepository_UpdateUser(t *testing.T) { } err = db.TestVerifyOplog(t, rw, u.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) require.Error(err) - assert.Equal("record not found", err.Error()) + assert.Contains(err.Error(), "record not found") return } require.NoError(err) @@ -435,7 +434,7 @@ func TestRepository_DeleteUser(t *testing.T) { }, wantRowsDeleted: 1, wantErr: true, - wantErrMsg: "delete user: failed record not found for", + wantErrMsg: "delete user: failed record not found:", }, } for _, tt := range tests { @@ -445,10 +444,10 @@ func TestRepository_DeleteUser(t *testing.T) { if tt.wantErr { require.Error(err) assert.Equal(0, deletedRows) - assert.True(strings.HasPrefix(err.Error(), tt.wantErrMsg)) + assert.Contains(err.Error(), tt.wantErrMsg) err = db.TestVerifyOplog(t, rw, tt.args.user.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) require.Error(err) - assert.Equal("record not found", err.Error()) + assert.Contains(err.Error(), "record not found") return } require.NoError(err) @@ -591,7 +590,7 @@ func TestRepository_LookupUserWithLogin(t *testing.T) { withAccountId: newAuthAcctWithoutVivify.PublicId, }, wantErr: true, - wantErrIs: db.ErrRecordNotFound, + wantErrIs: errors.ErrRecordNotFound, }, { name: "missing auth acct id", @@ -599,7 +598,7 @@ func TestRepository_LookupUserWithLogin(t *testing.T) { withAccountId: "", }, wantErr: true, - wantErrIs: db.ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "existing-auth-account", @@ -628,7 +627,7 @@ func TestRepository_LookupUserWithLogin(t *testing.T) { withAccountId: id, }, wantErr: true, - wantErrIs: db.ErrRecordNotFound, + wantErrIs: errors.ErrRecordNotFound, }, { name: "bad-auth-account-id-with-vivify", @@ -639,7 +638,7 @@ func TestRepository_LookupUserWithLogin(t *testing.T) { }, }, wantErr: true, - wantErrIs: db.ErrRecordNotFound, + wantErrIs: errors.ErrRecordNotFound, }, } for _, tt := range tests { @@ -729,7 +728,7 @@ func TestRepository_associateUserWithAccounts(t *testing.T) { }(), }, wantErr: true, - wantErrIs: db.ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "missing-userId", @@ -740,7 +739,7 @@ func TestRepository_associateUserWithAccounts(t *testing.T) { }(), }, wantErr: true, - wantErrIs: db.ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "already-properly-assoc", @@ -764,7 +763,7 @@ func TestRepository_associateUserWithAccounts(t *testing.T) { }(), }, wantErr: true, - wantErrIs: db.ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "assoc-with-diff-user-withDisassociateOption", @@ -777,7 +776,7 @@ func TestRepository_associateUserWithAccounts(t *testing.T) { }(), }, wantErr: true, - wantErrIs: db.ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "bad-acct-id", @@ -789,7 +788,7 @@ func TestRepository_associateUserWithAccounts(t *testing.T) { }(), }, wantErr: true, - wantErrIs: db.ErrRecordNotFound, + wantErrIs: errors.ErrRecordNotFound, }, { name: "bad-user-id-not-associated-account", @@ -885,7 +884,7 @@ func TestRepository_dissociateUserWithAccount(t *testing.T) { }(), }, wantErr: true, - wantErrIs: db.ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "missing-userId", @@ -896,7 +895,7 @@ func TestRepository_dissociateUserWithAccount(t *testing.T) { }(), }, wantErr: true, - wantErrIs: db.ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "already-properly-disassoc", @@ -908,7 +907,7 @@ func TestRepository_dissociateUserWithAccount(t *testing.T) { }(), }, wantErr: true, - wantErrIs: db.ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "assoc-with-diff-user", @@ -921,7 +920,7 @@ func TestRepository_dissociateUserWithAccount(t *testing.T) { }(), }, wantErr: true, - wantErrIs: db.ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "bad-acct-id", @@ -933,7 +932,7 @@ func TestRepository_dissociateUserWithAccount(t *testing.T) { }(), }, wantErr: true, - wantErrIs: db.ErrRecordNotFound, + wantErrIs: errors.ErrRecordNotFound, }, { name: "bad-user-id-not-associated-account", @@ -945,7 +944,7 @@ func TestRepository_dissociateUserWithAccount(t *testing.T) { }(), }, wantErr: true, - wantErrIs: db.ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "bad-user-id", diff --git a/internal/iam/resource.go b/internal/iam/resource.go index cf081fda7..2c5ae7ac0 100644 --- a/internal/iam/resource.go +++ b/internal/iam/resource.go @@ -2,10 +2,11 @@ package iam import ( "context" - "errors" + stderrors "errors" "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/types/action" "github.com/hashicorp/boundary/internal/types/resource" "github.com/hashicorp/boundary/internal/types/scope" @@ -49,13 +50,13 @@ type ResourceWithScope interface { // LookupScope looks up the resource's scope func LookupScope(ctx context.Context, reader db.Reader, resource ResourceWithScope) (*Scope, error) { if reader == nil { - return nil, errors.New("error reader is nil for LookupScope") + return nil, stderrors.New("error reader is nil for LookupScope") } if resource == nil { - return nil, errors.New("error resource is nil for LookupScope") + return nil, stderrors.New("error resource is nil for LookupScope") } if resource.GetPublicId() == "" { - return nil, fmt.Errorf("LookupScope: scope id is unset %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("LookupScope: scope id is unset %w", errors.ErrInvalidParameter) } if resource.GetScopeId() == "" { // try to retrieve it from db with it's scope id @@ -64,7 +65,7 @@ func LookupScope(ctx context.Context, reader db.Reader, resource ResourceWithSco } // if it's still not set after getting it from the db... if resource.GetScopeId() == "" { - return nil, errors.New("error scope is unset for LookupScope") + return nil, stderrors.New("error scope is unset for LookupScope") } } var p Scope @@ -80,12 +81,12 @@ func validateScopeForWrite(ctx context.Context, r db.Reader, resource ResourceWi if opType == db.CreateOp { if resource.GetScopeId() == "" { - return errors.New("error scope id not set for user write") + return stderrors.New("error scope id not set for user write") } ps, err := LookupScope(ctx, r, resource) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { - return errors.New("scope is not found") + if errors.Is(err, errors.ErrRecordNotFound) { + return stderrors.New("scope is not found") } return err } @@ -102,7 +103,7 @@ func validateScopeForWrite(ctx context.Context, r db.Reader, resource ResourceWi } if opType == db.UpdateOp && resource.GetScopeId() != "" { if contains(opts.WithFieldMaskPaths, "ScopeId") || contains(opts.WithNullPaths, "ScopeId") { - return errors.New("not allowed to change a resource's scope") + return stderrors.New("not allowed to change a resource's scope") } } return nil diff --git a/internal/iam/resource_test.go b/internal/iam/resource_test.go index d12b1158d..7b587b0fb 100644 --- a/internal/iam/resource_test.go +++ b/internal/iam/resource_test.go @@ -49,6 +49,6 @@ func Test_LookupScope(t *testing.T) { user2 := allocUser() s, err = LookupScope(context.Background(), w, &user2) assert.Nil(s) - assert.Equal("LookupScope: scope id is unset invalid parameter", err.Error()) + assert.Contains(err.Error(), "LookupScope: scope id is unset invalid parameter") }) } diff --git a/internal/iam/role.go b/internal/iam/role.go index 56b0a30bf..c2fd19db0 100644 --- a/internal/iam/role.go +++ b/internal/iam/role.go @@ -2,10 +2,11 @@ package iam import ( "context" - "errors" + stderrors "errors" "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam/store" "github.com/hashicorp/boundary/internal/types/action" "github.com/hashicorp/boundary/internal/types/resource" @@ -32,7 +33,7 @@ var _ db.VetForWriter = (*Role)(nil) // allowed options include: withDescripion, WithName, withGrantScopeId. func NewRole(scopeId string, opt ...Option) (*Role, error) { if scopeId == "" { - return nil, fmt.Errorf("new role: missing scope id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new role: missing scope id %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) r := &Role{ @@ -63,7 +64,7 @@ func (r *Role) Clone() interface{} { // VetForWrite implements db.VetForWrite() interface. func (role *Role) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if role.PublicId == "" { - return errors.New("error public id is empty string for role write") + return stderrors.New("error public id is empty string for role write") } if err := validateScopeForWrite(ctx, r, role, opType, opt...); err != nil { return err diff --git a/internal/iam/role_grant.go b/internal/iam/role_grant.go index 4c44f2cdc..f83fbdbcd 100644 --- a/internal/iam/role_grant.go +++ b/internal/iam/role_grant.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam/store" "github.com/hashicorp/boundary/internal/perms" "google.golang.org/protobuf/proto" @@ -25,10 +26,10 @@ var _ db.VetForWriter = (*RoleGrant)(nil) // NewRoleGrant creates a new in memory role grant func NewRoleGrant(roleId string, grant string, opt ...Option) (*RoleGrant, error) { if roleId == "" { - return nil, fmt.Errorf("new role grant: role id is not set: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new role grant: role id is not set: %w", errors.ErrInvalidParameter) } if grant == "" { - return nil, fmt.Errorf("new role grant: grant is empty: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new role grant: grant is empty: %w", errors.ErrInvalidParameter) } // Validate that the grant parses successfully. Note that we fake the scope @@ -65,7 +66,7 @@ func (g *RoleGrant) Clone() interface{} { // VetForWrite implements db.VetForWrite() interface func (g *RoleGrant) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if g.RawGrant == "" { - return fmt.Errorf("vet role grant for writing: grant is empty: %w", db.ErrInvalidParameter) + return fmt.Errorf("vet role grant for writing: grant is empty: %w", errors.ErrInvalidParameter) } // Validate that the grant parses successfully. Note that we fake the scope diff --git a/internal/iam/role_grant_test.go b/internal/iam/role_grant_test.go index 5fd80c51d..0f7571ab0 100644 --- a/internal/iam/role_grant_test.go +++ b/internal/iam/role_grant_test.go @@ -2,11 +2,11 @@ package iam import ( "context" - "errors" "strings" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam/store" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -41,7 +41,7 @@ func TestRoleGrant_Create(t *testing.T) { grant: "id=*;type=*;actions=*", }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "nil-grant", @@ -50,7 +50,7 @@ func TestRoleGrant_Create(t *testing.T) { grant: "", }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, create: true, }, { diff --git a/internal/iam/role_test.go b/internal/iam/role_test.go index 56266f870..681e68753 100644 --- a/internal/iam/role_test.go +++ b/internal/iam/role_test.go @@ -2,12 +2,12 @@ package iam import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/db" dbassert "github.com/hashicorp/boundary/internal/db/assert" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam/store" "github.com/hashicorp/boundary/internal/oplog" "github.com/hashicorp/boundary/internal/types/action" @@ -71,8 +71,8 @@ func TestNewRole(t *testing.T) { opt: []Option{WithName(id)}, }, wantErr: true, - wantErrMsg: "new role: missing scope id invalid parameter", - wantIsErr: db.ErrInvalidParameter, + wantErrMsg: "new role: missing scope id invalid parameter:", + wantIsErr: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -81,7 +81,7 @@ func TestNewRole(t *testing.T) { got, err := NewRole(tt.args.scopePublicId, tt.args.opt...) if tt.wantErr { require.Error(err) - assert.Equal(tt.wantErrMsg, err.Error()) + assert.Contains(err.Error(), tt.wantErrMsg) if tt.wantIsErr != nil { assert.True(errors.Is(err, tt.wantIsErr)) } @@ -427,7 +427,7 @@ func Test_RoleUpdate(t *testing.T) { assert.Equal(tt.wantErrMsg, err.Error()) err = db.TestVerifyOplog(t, rw, role.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) require.Error(err) - assert.Equal("record not found", err.Error()) + assert.Contains(err.Error(), "record not found:") return } require.NoError(err) @@ -526,7 +526,7 @@ func Test_RoleDelete(t *testing.T) { foundRole.PublicId = tt.role.GetPublicId() err = rw.LookupByPublicId(context.Background(), &foundRole) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/iam/scope.go b/internal/iam/scope.go index 5b93f889e..596d5b249 100644 --- a/internal/iam/scope.go +++ b/internal/iam/scope.go @@ -2,11 +2,12 @@ package iam import ( "context" - "errors" + stderrors "errors" "fmt" "strings" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam/store" "github.com/hashicorp/boundary/internal/types/action" "github.com/hashicorp/boundary/internal/types/resource" @@ -55,7 +56,7 @@ func NewProject(orgPublicId string, opt ...Option) (*Scope, error) { // used to determine the type of the child. func newScope(parent *Scope, opt ...Option) (*Scope, error) { if parent == nil || parent.PublicId == "" { - return nil, fmt.Errorf("new scope: child scope is missing its parent: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new scope: child scope is missing its parent: %w", errors.ErrInvalidParameter) } var typ scope.Type switch { @@ -65,7 +66,7 @@ func newScope(parent *Scope, opt ...Option) (*Scope, error) { typ = scope.Project } if typ == scope.Unknown { - return nil, fmt.Errorf("new scope: unknown type of scope to create: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new scope: unknown type of scope to create: %w", errors.ErrInvalidParameter) } opts := getOpts(opt...) @@ -100,31 +101,31 @@ func (s *Scope) Clone() interface{} { // the scope before writing it to the db. func (s *Scope) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if s.Type == scope.Unknown.String() { - return errors.New("unknown scope type for scope write") + return stderrors.New("unknown scope type for scope write") } if s.PublicId == "" { - return errors.New("public id is empty string for scope write") + return stderrors.New("public id is empty string for scope write") } if opType == db.UpdateOp { dbOptions := db.GetOpts(opt...) for _, path := range dbOptions.WithFieldMaskPaths { switch path { case "ParentId": - return errors.New("you cannot change a scope's parent") + return stderrors.New("you cannot change a scope's parent") case "Type": - return errors.New("you cannot change a scope's type") + return stderrors.New("you cannot change a scope's type") } } } if opType == db.CreateOp { switch { case s.Type == scope.Global.String(): - return errors.New("global scope cannot be created") + return stderrors.New("global scope cannot be created") case s.ParentId == "": - return errors.New("scope must have a parent") + return stderrors.New("scope must have a parent") case s.Type == scope.Org.String(): if s.ParentId != "global" { - return errors.New(`org's parent must be "global"`) + return stderrors.New(`org's parent must be "global"`) } case s.Type == scope.Project.String(): parentScope := allocScope() @@ -133,7 +134,7 @@ func (s *Scope) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, return fmt.Errorf("unable to verify project's org scope: %w", err) } if parentScope.Type != scope.Org.String() { - return errors.New("project parent scope is not an org") + return stderrors.New("project parent scope is not an org") } } } @@ -153,10 +154,10 @@ func (*Scope) Actions() map[string]action.Type { // GetScope returns the scope for the "scope" if there is one defined func (s *Scope) GetScope(ctx context.Context, r db.Reader) (*Scope, error) { if r == nil { - return nil, errors.New("error db is nil for get scope") + return nil, stderrors.New("error db is nil for get scope") } if s.PublicId == "" { - return nil, errors.New("unable to get scope with unset public id") + return nil, stderrors.New("unable to get scope with unset public id") } if s.Type == "" && s.ParentId == "" { if err := r.LookupByPublicId(ctx, s); err != nil { diff --git a/internal/iam/scope_test.go b/internal/iam/scope_test.go index 9472b7047..2494a5229 100644 --- a/internal/iam/scope_test.go +++ b/internal/iam/scope_test.go @@ -42,14 +42,14 @@ func TestScope_New(t *testing.T) { s, err := newScope(nil) require.Error(err) require.Nil(s) - assert.Equal("new scope: child scope is missing its parent: invalid parameter", err.Error()) + assert.Contains(err.Error(), "new scope: child scope is missing its parent: invalid parameter") }) t.Run("proj-scope-with-no-org", func(t *testing.T) { assert, require := assert.New(t), require.New(t) s, err := NewProject("") require.Error(err) require.Nil(s) - assert.Equal("error creating new project: new scope: child scope is missing its parent: invalid parameter", err.Error()) + assert.Contains(err.Error(), "error creating new project: new scope: child scope is missing its parent: invalid parameter") }) } func TestScope_Create(t *testing.T) { diff --git a/internal/iam/user.go b/internal/iam/user.go index 495070a18..b66726d56 100644 --- a/internal/iam/user.go +++ b/internal/iam/user.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam/store" "github.com/hashicorp/boundary/internal/types/action" "github.com/hashicorp/boundary/internal/types/resource" @@ -33,7 +34,7 @@ var _ db.VetForWriter = (*User)(nil) func NewUser(scopeId string, opt ...Option) (*User, error) { opts := getOpts(opt...) if scopeId == "" { - return nil, fmt.Errorf("new user: missing scope id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new user: missing scope id %w", errors.ErrInvalidParameter) } u := &User{ User: &store.User{ @@ -63,7 +64,7 @@ func (u *User) Clone() interface{} { // before it's written. func (u *User) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if u.PublicId == "" { - return fmt.Errorf("user vet for write: missing public id: %w", db.ErrInvalidParameter) + return fmt.Errorf("user vet for write: missing public id: %w", errors.ErrInvalidParameter) } if err := validateScopeForWrite(ctx, r, u, opType, opt...); err != nil { return err diff --git a/internal/iam/user_test.go b/internal/iam/user_test.go index bb961868f..b59243be8 100644 --- a/internal/iam/user_test.go +++ b/internal/iam/user_test.go @@ -64,7 +64,7 @@ func TestNewUser(t *testing.T) { got, err := NewUser(tt.args.orgPublicId, tt.args.opt...) if tt.wantErr { require.Error(err) - assert.Equal(tt.wantErrMsg, err.Error()) + assert.Contains(err.Error(), tt.wantErrMsg) return } require.NoError(err) diff --git a/internal/kms/database_key.go b/internal/kms/database_key.go index d24f728dc..6004a1dec 100644 --- a/internal/kms/database_key.go +++ b/internal/kms/database_key.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms/store" "google.golang.org/protobuf/proto" ) @@ -22,7 +23,7 @@ type DatabaseKey struct { // are currently supported. func NewDatabaseKey(rootKeyId string, opt ...Option) (*DatabaseKey, error) { if rootKeyId == "" { - return nil, fmt.Errorf("new root key: missing root key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new root key: missing root key id: %w", errors.ErrInvalidParameter) } c := &DatabaseKey{ DatabaseKey: &store.DatabaseKey{ @@ -51,15 +52,15 @@ func (k *DatabaseKey) Clone() interface{} { // before it's written. func (k *DatabaseKey) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if k.PrivateId == "" { - return fmt.Errorf("database key vet for write: missing private id: %w", db.ErrInvalidParameter) + return fmt.Errorf("database key vet for write: missing private id: %w", errors.ErrInvalidParameter) } switch opType { case db.CreateOp: if k.RootKeyId == "" { - return fmt.Errorf("database key vet for write: missing root key id: %w", db.ErrInvalidParameter) + return fmt.Errorf("database key vet for write: missing root key id: %w", errors.ErrInvalidParameter) } case db.UpdateOp: - return fmt.Errorf("database key vet for write: key is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("database key vet for write: key is immutable: %w", errors.ErrInvalidParameter) } return nil } diff --git a/internal/kms/database_key_test.go b/internal/kms/database_key_test.go index c6e7d28db..4f98653b8 100644 --- a/internal/kms/database_key_test.go +++ b/internal/kms/database_key_test.go @@ -2,10 +2,10 @@ package kms_test import ( "context" - "errors" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/stretchr/testify/assert" @@ -41,7 +41,7 @@ func TestDatabaseKey_Create(t *testing.T) { name: "empty-rootKeyId", args: args{}, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid", @@ -141,7 +141,7 @@ func TestDatabaseKey_Delete(t *testing.T) { foundKey.PrivateId = tt.key.PrivateId err = rw.LookupById(context.Background(), &foundKey) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/kms/database_key_version.go b/internal/kms/database_key_version.go index e0e6208cd..5d79b6372 100644 --- a/internal/kms/database_key_version.go +++ b/internal/kms/database_key_version.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms/store" wrapping "github.com/hashicorp/go-kms-wrapping" "github.com/hashicorp/go-kms-wrapping/structwrapping" @@ -24,13 +25,13 @@ type DatabaseKeyVersion struct { // currently supported. func NewDatabaseKeyVersion(databaseKeyId string, key []byte, rootKeyVersionId string, opt ...Option) (*DatabaseKeyVersion, error) { if databaseKeyId == "" { - return nil, fmt.Errorf("new database key version: missing database key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new database key version: missing database key id: %w", errors.ErrInvalidParameter) } if len(key) == 0 { - return nil, fmt.Errorf("new database key version: missing key: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new database key version: missing key: %w", errors.ErrInvalidParameter) } if rootKeyVersionId == "" { - return nil, fmt.Errorf("new database key version: missing root key version id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new database key version: missing root key version id: %w", errors.ErrInvalidParameter) } k := &DatabaseKeyVersion{ @@ -62,21 +63,21 @@ func (k *DatabaseKeyVersion) Clone() interface{} { // version before it's written. func (k *DatabaseKeyVersion) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if k.PrivateId == "" { - return fmt.Errorf("database key version vet for write: missing private id: %w", db.ErrInvalidParameter) + return fmt.Errorf("database key version vet for write: missing private id: %w", errors.ErrInvalidParameter) } switch opType { case db.CreateOp: if k.CtKey == nil { - return fmt.Errorf("database key version vet for write: missing key: %w", db.ErrInvalidParameter) + return fmt.Errorf("database key version vet for write: missing key: %w", errors.ErrInvalidParameter) } if k.DatabaseKeyId == "" { - return fmt.Errorf("database key version vet for write: missing database key id: %w", db.ErrInvalidParameter) + return fmt.Errorf("database key version vet for write: missing database key id: %w", errors.ErrInvalidParameter) } if k.RootKeyVersionId == "" { - return fmt.Errorf("database key version vet for write: missing root key version id: %w", db.ErrInvalidParameter) + return fmt.Errorf("database key version vet for write: missing root key version id: %w", errors.ErrInvalidParameter) } case db.UpdateOp: - return fmt.Errorf("database key version vet for write: key is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("database key version vet for write: key is immutable: %w", errors.ErrInvalidParameter) } return nil } diff --git a/internal/kms/database_key_version_test.go b/internal/kms/database_key_version_test.go index 3e1344e46..17e3a962e 100644 --- a/internal/kms/database_key_version_test.go +++ b/internal/kms/database_key_version_test.go @@ -2,10 +2,10 @@ package kms_test import ( "context" - "errors" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/stretchr/testify/assert" @@ -49,7 +49,7 @@ func TestDatabaseKeyVersion_Create(t *testing.T) { rootKeyVersionId: rkv.PrivateId, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-key", @@ -58,7 +58,7 @@ func TestDatabaseKeyVersion_Create(t *testing.T) { rootKeyVersionId: rkv.PrivateId, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-root-key-version-id", @@ -67,7 +67,7 @@ func TestDatabaseKeyVersion_Create(t *testing.T) { key: []byte("database key"), }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid", @@ -175,7 +175,7 @@ func TestDatabaseKeyVersion_Delete(t *testing.T) { foundKey.PrivateId = tt.key.PrivateId err = rw.LookupById(context.Background(), &foundKey) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/kms/kms.go b/internal/kms/kms.go index ee48c41f0..9dcdd5274 100644 --- a/internal/kms/kms.go +++ b/internal/kms/kms.go @@ -2,7 +2,7 @@ package kms import ( "context" - "errors" + stderrors "errors" "fmt" "sync" @@ -62,7 +62,7 @@ type Kms struct { // NewKms takes in a repo and returns a Kms. Supported options: WithLogger. func NewKms(repo *Repository, opt ...Option) (*Kms, error) { if repo == nil { - return nil, errors.New("new kms created without an underlying repo") + return nil, stderrors.New("new kms created without an underlying repo") } opts := getOpts(opt...) @@ -147,13 +147,13 @@ func generateKeyId(scopeId string, purpose KeyPurpose, version uint32) string { // decryption. func (k *Kms) GetWrapper(ctx context.Context, scopeId string, purpose KeyPurpose, opt ...Option) (wrapping.Wrapper, error) { if scopeId == "" { - return nil, errors.New("no scope ID provided") + return nil, stderrors.New("no scope ID provided") } switch purpose { case KeyPurposeOplog, KeyPurposeDatabase, KeyPurposeTokens, KeyPurposeSessions: case KeyPurposeUnknown: - return nil, errors.New("key purpose not specified") + return nil, stderrors.New("key purpose not specified") default: return nil, fmt.Errorf("unsupported purpose %q", purpose) } @@ -219,7 +219,7 @@ func (k *Kms) loadRoot(ctx context.Context, scopeId string, opt ...Option) (*mul externalWrappers := k.externalScopeCache[scope.Global.String()] k.externalScopeCacheMutex.Unlock() if externalWrappers == nil { - return nil, "", errors.New("could not find kms information at either the needed scope or global fallback") + return nil, "", stderrors.New("could not find kms information at either the needed scope or global fallback") } externalWrappers.m.RLock() diff --git a/internal/kms/oplog_key.go b/internal/kms/oplog_key.go index dd7377954..c29f6aeb4 100644 --- a/internal/kms/oplog_key.go +++ b/internal/kms/oplog_key.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms/store" "google.golang.org/protobuf/proto" ) @@ -22,7 +23,7 @@ type OplogKey struct { // are currently supported. func NewOplogKey(rootKeyId string, opt ...Option) (*OplogKey, error) { if rootKeyId == "" { - return nil, fmt.Errorf("new root key: missing root key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new root key: missing root key id: %w", errors.ErrInvalidParameter) } c := &OplogKey{ OplogKey: &store.OplogKey{ @@ -51,11 +52,11 @@ func (k *OplogKey) Clone() interface{} { // before it's written. func (k *OplogKey) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if k.PrivateId == "" { - return fmt.Errorf("oplog key vet for write: missing private id: %w", db.ErrInvalidParameter) + return fmt.Errorf("oplog key vet for write: missing private id: %w", errors.ErrInvalidParameter) } if opType == db.CreateOp { if k.RootKeyId == "" { - return fmt.Errorf("oplog key vet for write: missing root key id: %w", db.ErrInvalidParameter) + return fmt.Errorf("oplog key vet for write: missing root key id: %w", errors.ErrInvalidParameter) } } return nil diff --git a/internal/kms/oplog_key_test.go b/internal/kms/oplog_key_test.go index e4197b604..4bb47ecdb 100644 --- a/internal/kms/oplog_key_test.go +++ b/internal/kms/oplog_key_test.go @@ -2,10 +2,10 @@ package kms_test import ( "context" - "errors" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/stretchr/testify/assert" @@ -41,7 +41,7 @@ func TestOplogKey_Create(t *testing.T) { name: "empty-rootKeyId", args: args{}, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid", @@ -141,7 +141,7 @@ func TestOplogKey_Delete(t *testing.T) { foundKey.PrivateId = tt.key.PrivateId err = rw.LookupById(context.Background(), &foundKey) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/kms/oplog_key_version.go b/internal/kms/oplog_key_version.go index a61284f55..fb1a3e973 100644 --- a/internal/kms/oplog_key_version.go +++ b/internal/kms/oplog_key_version.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms/store" wrapping "github.com/hashicorp/go-kms-wrapping" "github.com/hashicorp/go-kms-wrapping/structwrapping" @@ -24,13 +25,13 @@ type OplogKeyVersion struct { // currently supported. func NewOplogKeyVersion(oplogKeyId string, key []byte, rootKeyVersionId string, opt ...Option) (*OplogKeyVersion, error) { if oplogKeyId == "" { - return nil, fmt.Errorf("new oplog key version: missing oplog key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new oplog key version: missing oplog key id: %w", errors.ErrInvalidParameter) } if len(key) == 0 { - return nil, fmt.Errorf("new oplog key version: missing key: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new oplog key version: missing key: %w", errors.ErrInvalidParameter) } if rootKeyVersionId == "" { - return nil, fmt.Errorf("new oplog key version: missing root key version id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new oplog key version: missing root key version id: %w", errors.ErrInvalidParameter) } k := &OplogKeyVersion{ @@ -62,17 +63,17 @@ func (k *OplogKeyVersion) Clone() interface{} { // version before it's written. func (k *OplogKeyVersion) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if k.PrivateId == "" { - return fmt.Errorf("oplog key version vet for write: missing private id: %w", db.ErrInvalidParameter) + return fmt.Errorf("oplog key version vet for write: missing private id: %w", errors.ErrInvalidParameter) } if opType == db.CreateOp { if k.CtKey == nil { - return fmt.Errorf("oplog key version vet for write: missing key: %w", db.ErrInvalidParameter) + return fmt.Errorf("oplog key version vet for write: missing key: %w", errors.ErrInvalidParameter) } if k.OplogKeyId == "" { - return fmt.Errorf("oplog key version vet for write: missing oplog key id: %w", db.ErrInvalidParameter) + return fmt.Errorf("oplog key version vet for write: missing oplog key id: %w", errors.ErrInvalidParameter) } if k.RootKeyVersionId == "" { - return fmt.Errorf("oplog key version vet for write: missing root key version id: %w", db.ErrInvalidParameter) + return fmt.Errorf("oplog key version vet for write: missing root key version id: %w", errors.ErrInvalidParameter) } } return nil diff --git a/internal/kms/oplog_key_version_test.go b/internal/kms/oplog_key_version_test.go index 8282a5fa7..e58363bee 100644 --- a/internal/kms/oplog_key_version_test.go +++ b/internal/kms/oplog_key_version_test.go @@ -2,10 +2,10 @@ package kms_test import ( "context" - "errors" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/stretchr/testify/assert" @@ -49,7 +49,7 @@ func TestOplogKeyVersion_Create(t *testing.T) { rootKeyVersionId: rkv.PrivateId, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-key", @@ -58,7 +58,7 @@ func TestOplogKeyVersion_Create(t *testing.T) { rootKeyVersionId: rkv.PrivateId, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-root-key-version-id", @@ -67,7 +67,7 @@ func TestOplogKeyVersion_Create(t *testing.T) { key: []byte("test key"), }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid", @@ -175,7 +175,7 @@ func TestOplogKeyVersion_Delete(t *testing.T) { foundKey.PrivateId = tt.key.PrivateId err = rw.LookupById(context.Background(), &foundKey) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/kms/repository.go b/internal/kms/repository.go index a40ecea44..24160982e 100644 --- a/internal/kms/repository.go +++ b/internal/kms/repository.go @@ -2,11 +2,12 @@ package kms import ( "context" - "errors" + stderrors "errors" "fmt" "io" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" wrapping "github.com/hashicorp/go-kms-wrapping" "github.com/hashicorp/go-kms-wrapping/wrappers/aead" "github.com/hashicorp/go-uuid" @@ -24,10 +25,10 @@ type Repository struct { // which sets a default limit on results returned by repo operations. func NewRepository(r db.Reader, w db.Writer, opt ...Option) (*Repository, error) { if r == nil { - return nil, errors.New("error creating db repository with nil reader") + return nil, stderrors.New("error creating db repository with nil reader") } if w == nil { - return nil, errors.New("error creating db repository with nil writer") + return nil, stderrors.New("error creating db repository with nil writer") } opts := getOpts(opt...) if opts.withLimit == 0 { @@ -78,19 +79,19 @@ type Keys map[KeyType]KeyIder // allows this capability to be shared with the iam repo. func CreateKeysTx(ctx context.Context, dbReader db.Reader, dbWriter db.Writer, rootWrapper wrapping.Wrapper, randomReader io.Reader, scopeId string) (Keys, error) { if dbReader == nil { - return nil, fmt.Errorf("create keys: missing db reader: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create keys: missing db reader: %w", errors.ErrInvalidParameter) } if dbWriter == nil { - return nil, fmt.Errorf("create keys: missing db writer: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create keys: missing db writer: %w", errors.ErrInvalidParameter) } if rootWrapper == nil { - return nil, fmt.Errorf("create keys: missing root wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create keys: missing root wrapper: %w", errors.ErrInvalidParameter) } if randomReader == nil { - return nil, fmt.Errorf("create keys: missing random reader: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create keys: missing random reader: %w", errors.ErrInvalidParameter) } if scopeId == "" { - return nil, fmt.Errorf("create keys: missing scope id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create keys: missing scope id: %w", errors.ErrInvalidParameter) } k, err := generateKey(randomReader) if err != nil { diff --git a/internal/kms/repository_database_key.go b/internal/kms/repository_database_key.go index 2fc461cf9..b12389103 100644 --- a/internal/kms/repository_database_key.go +++ b/internal/kms/repository_database_key.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" wrapping "github.com/hashicorp/go-kms-wrapping" ) @@ -36,17 +37,17 @@ func (r *Repository) CreateDatabaseKey(ctx context.Context, rkvWrapper wrapping. // a db.TxHandler and allows this capability to be shared with the iam repo. func createDatabaseKeyTx(ctx context.Context, r db.Reader, w db.Writer, rkvWrapper wrapping.Wrapper, key []byte) (*DatabaseKey, *DatabaseKeyVersion, error) { if rkvWrapper == nil { - return nil, nil, fmt.Errorf("create database key: missing key wrapper: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create database key: missing key wrapper: %w", errors.ErrInvalidParameter) } if len(key) == 0 { - return nil, nil, fmt.Errorf("create database key: missing key: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create database key: missing key: %w", errors.ErrInvalidParameter) } rootKeyVersionId := rkvWrapper.KeyID() switch { case !strings.HasPrefix(rootKeyVersionId, RootKeyVersionPrefix): - return nil, nil, fmt.Errorf("create database key: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create database key: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, errors.ErrInvalidParameter) case rootKeyVersionId == "": - return nil, nil, fmt.Errorf("create database key: missing root key version id: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create database key: missing root key version id: %w", errors.ErrInvalidParameter) } rv := AllocRootKeyVersion() rv.PrivateId = rootKeyVersionId @@ -92,7 +93,7 @@ func createDatabaseKeyTx(ctx context.Context, r db.Reader, w db.Writer, rkvWrapp // found, it will return nil, nil. func (r *Repository) LookupDatabaseKey(ctx context.Context, privateId string, opt ...Option) (*DatabaseKey, error) { if privateId == "" { - return nil, fmt.Errorf("lookup database key: missing private id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup database key: missing private id: %w", errors.ErrInvalidParameter) } k := AllocDatabaseKey() k.PrivateId = privateId @@ -107,7 +108,7 @@ func (r *Repository) LookupDatabaseKey(ctx context.Context, privateId string, op // are ignored. func (r *Repository) DeleteDatabaseKey(ctx context.Context, privateId string, opt ...Option) (int, error) { if privateId == "" { - return db.NoRowsAffected, fmt.Errorf("delete database key: missing private id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete database key: missing private id: %w", errors.ErrInvalidParameter) } k := AllocDatabaseKey() k.PrivateId = privateId @@ -125,7 +126,7 @@ func (r *Repository) DeleteDatabaseKey(ctx context.Context, privateId string, op // no oplog entries for root keys rowsDeleted, err = w.Delete(ctx, dk) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, diff --git a/internal/kms/repository_database_key_test.go b/internal/kms/repository_database_key_test.go index 542548f39..55b438c6b 100644 --- a/internal/kms/repository_database_key_test.go +++ b/internal/kms/repository_database_key_test.go @@ -2,11 +2,11 @@ package kms_test import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -57,7 +57,7 @@ func TestRepository_CreateDatabaseKey(t *testing.T) { keyWrapper: rkvWrapper, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-key", @@ -67,7 +67,7 @@ func TestRepository_CreateDatabaseKey(t *testing.T) { key: []byte(""), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "nil-wrapper", @@ -77,7 +77,7 @@ func TestRepository_CreateDatabaseKey(t *testing.T) { keyWrapper: nil, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "not-rkv-wrapper", @@ -87,7 +87,7 @@ func TestRepository_CreateDatabaseKey(t *testing.T) { keyWrapper: wrapper, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "wrapper-missing-id", @@ -104,7 +104,7 @@ func TestRepository_CreateDatabaseKey(t *testing.T) { }(), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -128,7 +128,7 @@ func TestRepository_CreateDatabaseKey(t *testing.T) { // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, dk.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) assert.NotNil(dv.CreateTime) foundKeyVersion, err := repo.LookupDatabaseKeyVersion(context.Background(), tt.args.keyWrapper, dv.PrivateId) @@ -138,7 +138,7 @@ func TestRepository_CreateDatabaseKey(t *testing.T) { // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, dv.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) }) } } @@ -183,7 +183,7 @@ func TestRepository_DeleteDatabaseKey(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "not-found", @@ -199,7 +199,7 @@ func TestRepository_DeleteDatabaseKey(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrRecordNotFound, + wantIsError: errors.ErrRecordNotFound, }, } for _, tt := range tests { @@ -215,7 +215,7 @@ func TestRepository_DeleteDatabaseKey(t *testing.T) { // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) @@ -223,12 +223,12 @@ func TestRepository_DeleteDatabaseKey(t *testing.T) { foundKey, err := repo.LookupDatabaseKey(context.Background(), tt.args.key.PrivateId) assert.Error(err) assert.Nil(foundKey) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/kms/repository_database_key_version.go b/internal/kms/repository_database_key_version.go index e9d64b5f5..8013279b2 100644 --- a/internal/kms/repository_database_key_version.go +++ b/internal/kms/repository_database_key_version.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" wrapping "github.com/hashicorp/go-kms-wrapping" ) @@ -13,20 +14,20 @@ import ( // version with its PrivateId. There are no valid options at this time. func (r *Repository) CreateDatabaseKeyVersion(ctx context.Context, rkvWrapper wrapping.Wrapper, databaseKeyId string, key []byte, opt ...Option) (*DatabaseKeyVersion, error) { if rkvWrapper == nil { - return nil, fmt.Errorf("create database key version: missing root key version wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create database key version: missing root key version wrapper: %w", errors.ErrInvalidParameter) } rootKeyVersionId := rkvWrapper.KeyID() switch { case !strings.HasPrefix(rootKeyVersionId, RootKeyVersionPrefix): - return nil, fmt.Errorf("create database key version: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, db.ErrInvalidParameter) + return nil, fmt.Errorf("create database key version: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, errors.ErrInvalidParameter) case rootKeyVersionId == "": - return nil, fmt.Errorf("create database key version: missing root key version id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create database key version: missing root key version id: %w", errors.ErrInvalidParameter) } if databaseKeyId == "" { - return nil, fmt.Errorf("create database key version: missing database key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create database key version: missing database key id: %w", errors.ErrInvalidParameter) } if len(key) == 0 { - return nil, fmt.Errorf("create database key version: missing key: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create database key version: missing key: %w", errors.ErrInvalidParameter) } kv := AllocDatabaseKeyVersion() id, err := newDatabaseKeyVersionId() @@ -65,10 +66,10 @@ func (r *Repository) CreateDatabaseKeyVersion(ctx context.Context, rkvWrapper wr // the key version is not found, it will return nil, nil. func (r *Repository) LookupDatabaseKeyVersion(ctx context.Context, keyWrapper wrapping.Wrapper, privateId string, opt ...Option) (*DatabaseKeyVersion, error) { if privateId == "" { - return nil, fmt.Errorf("lookup database key version: missing private id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup database key version: missing private id: %w", errors.ErrInvalidParameter) } if keyWrapper == nil { - return nil, fmt.Errorf("lookup database key version: missing key wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup database key version: missing key wrapper: %w", errors.ErrInvalidParameter) } k := AllocDatabaseKeyVersion() k.PrivateId = privateId @@ -86,7 +87,7 @@ func (r *Repository) LookupDatabaseKeyVersion(ctx context.Context, keyWrapper wr // are ignored. func (r *Repository) DeleteDatabaseKeyVersion(ctx context.Context, privateId string, opt ...Option) (int, error) { if privateId == "" { - return db.NoRowsAffected, fmt.Errorf("delete database key version: missing private id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete database key version: missing private id: %w", errors.ErrInvalidParameter) } k := AllocDatabaseKeyVersion() k.PrivateId = privateId @@ -104,7 +105,7 @@ func (r *Repository) DeleteDatabaseKeyVersion(ctx context.Context, privateId str // no oplog entries for the key version rowsDeleted, err = w.Delete(ctx, dk) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, @@ -117,20 +118,20 @@ func (r *Repository) DeleteDatabaseKeyVersion(ctx context.Context, privateId str // LatestDatabaseKeyVersion searches for the key version with the highest // version number. When no results are found, it returns nil, -// db.ErrRecordNotFound. +// errors.ErrRecordNotFound. func (r *Repository) LatestDatabaseKeyVersion(ctx context.Context, rkvWrapper wrapping.Wrapper, databaseKeyId string, opt ...Option) (*DatabaseKeyVersion, error) { if databaseKeyId == "" { - return nil, fmt.Errorf("latest database key version: missing database key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("latest database key version: missing database key id: %w", errors.ErrInvalidParameter) } if rkvWrapper == nil { - return nil, fmt.Errorf("latest database key version: missing root key version wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("latest database key version: missing root key version wrapper: %w", errors.ErrInvalidParameter) } var foundKeys []*DatabaseKeyVersion if err := r.reader.SearchWhere(ctx, &foundKeys, "database_key_id = ?", []interface{}{databaseKeyId}, db.WithLimit(1), db.WithOrder("version desc")); err != nil { return nil, fmt.Errorf("latest database key version: failed %w for %s", err, databaseKeyId) } if len(foundKeys) == 0 { - return nil, db.ErrRecordNotFound + return nil, errors.ErrRecordNotFound } if err := foundKeys[0].Decrypt(ctx, rkvWrapper); err != nil { return nil, fmt.Errorf("latest database key version: %w", err) @@ -141,10 +142,10 @@ func (r *Repository) LatestDatabaseKeyVersion(ctx context.Context, rkvWrapper wr // ListDatabaseKeyVersions will lists versions of a key. Supports the WithLimit option. func (r *Repository) ListDatabaseKeyVersions(ctx context.Context, rkvWrapper wrapping.Wrapper, databaseKeyId string, opt ...Option) ([]DekVersion, error) { if databaseKeyId == "" { - return nil, fmt.Errorf("list database key versions: missing database key id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list database key versions: missing database key id %w", errors.ErrInvalidParameter) } if rkvWrapper == nil { - return nil, fmt.Errorf("list database key versions: missing root key version wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list database key versions: missing root key version wrapper: %w", errors.ErrInvalidParameter) } var versions []*DatabaseKeyVersion err := r.list(ctx, &versions, "database_key_id = ?", []interface{}{databaseKeyId}, opt...) diff --git a/internal/kms/repository_database_key_version_test.go b/internal/kms/repository_database_key_version_test.go index 54a3c2456..c1606b6f4 100644 --- a/internal/kms/repository_database_key_version_test.go +++ b/internal/kms/repository_database_key_version_test.go @@ -2,11 +2,11 @@ package kms_test import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -67,7 +67,7 @@ func TestRepository_CreateDatabaseKeyVersion(t *testing.T) { databaseKeyId: dk.PrivateId, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "nil-wrapper", @@ -76,7 +76,7 @@ func TestRepository_CreateDatabaseKeyVersion(t *testing.T) { keyWrapper: nil, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -100,7 +100,7 @@ func TestRepository_CreateDatabaseKeyVersion(t *testing.T) { // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, k.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } @@ -147,7 +147,7 @@ func TestRepository_DeleteDatabaseKeyVersion(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "not-found", @@ -163,7 +163,7 @@ func TestRepository_DeleteDatabaseKeyVersion(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrRecordNotFound, + wantIsError: errors.ErrRecordNotFound, }, } for _, tt := range tests { @@ -178,7 +178,7 @@ func TestRepository_DeleteDatabaseKeyVersion(t *testing.T) { } err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) @@ -186,12 +186,12 @@ func TestRepository_DeleteDatabaseKeyVersion(t *testing.T) { foundKey, err := repo.LookupDatabaseKeyVersion(context.Background(), wrapper, tt.args.key.PrivateId) assert.Error(err) assert.Nil(foundKey) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } @@ -236,14 +236,14 @@ func TestRepository_LatestDatabaseKeyVersion(t *testing.T) { createCnt: 0, keyWrapper: rkvWrapper, wantErr: true, - wantIsError: db.ErrRecordNotFound, + wantIsError: errors.ErrRecordNotFound, }, { name: "nil-wrapper", createCnt: 5, keyWrapper: nil, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { diff --git a/internal/kms/repository_oplog_key.go b/internal/kms/repository_oplog_key.go index a9495886d..a1b4b94f7 100644 --- a/internal/kms/repository_oplog_key.go +++ b/internal/kms/repository_oplog_key.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" wrapping "github.com/hashicorp/go-kms-wrapping" ) @@ -36,17 +37,17 @@ func (r *Repository) CreateOplogKey(ctx context.Context, rkvWrapper wrapping.Wra // a db.TxHandler and allows this capability to be shared with the iam repo. func createOplogKeyTx(ctx context.Context, r db.Reader, w db.Writer, rkvWrapper wrapping.Wrapper, key []byte) (*OplogKey, *OplogKeyVersion, error) { if rkvWrapper == nil { - return nil, nil, fmt.Errorf("create oplog key: missing key wrapper: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create oplog key: missing key wrapper: %w", errors.ErrInvalidParameter) } if len(key) == 0 { - return nil, nil, fmt.Errorf("create oplog key: missing key: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create oplog key: missing key: %w", errors.ErrInvalidParameter) } rootKeyVersionId := rkvWrapper.KeyID() switch { case !strings.HasPrefix(rootKeyVersionId, RootKeyVersionPrefix): - return nil, nil, fmt.Errorf("create oplog key: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create oplog key: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, errors.ErrInvalidParameter) case rootKeyVersionId == "": - return nil, nil, fmt.Errorf("create oplog key: missing root key version id: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create oplog key: missing root key version id: %w", errors.ErrInvalidParameter) } rv := AllocRootKeyVersion() rv.PrivateId = rootKeyVersionId @@ -92,7 +93,7 @@ func createOplogKeyTx(ctx context.Context, r db.Reader, w db.Writer, rkvWrapper // found, it will return nil, nil. func (r *Repository) LookupOplogKey(ctx context.Context, privateId string, opt ...Option) (*OplogKey, error) { if privateId == "" { - return nil, fmt.Errorf("lookup oplog key: missing private id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup oplog key: missing private id: %w", errors.ErrInvalidParameter) } k := AllocOplogKey() k.PrivateId = privateId @@ -107,7 +108,7 @@ func (r *Repository) LookupOplogKey(ctx context.Context, privateId string, opt . // are ignored. func (r *Repository) DeleteOplogKey(ctx context.Context, privateId string, opt ...Option) (int, error) { if privateId == "" { - return db.NoRowsAffected, fmt.Errorf("delete oplog key: missing private id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete oplog key: missing private id: %w", errors.ErrInvalidParameter) } k := AllocOplogKey() k.PrivateId = privateId @@ -125,7 +126,7 @@ func (r *Repository) DeleteOplogKey(ctx context.Context, privateId string, opt . // no oplog entries for root keys rowsDeleted, err = w.Delete(ctx, dk) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, diff --git a/internal/kms/repository_oplog_key_test.go b/internal/kms/repository_oplog_key_test.go index 0b933855e..f1d7c8ce2 100644 --- a/internal/kms/repository_oplog_key_test.go +++ b/internal/kms/repository_oplog_key_test.go @@ -2,11 +2,11 @@ package kms_test import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -57,7 +57,7 @@ func TestRepository_CreateOplogKey(t *testing.T) { keyWrapper: rkvWrapper, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-key", @@ -67,7 +67,7 @@ func TestRepository_CreateOplogKey(t *testing.T) { key: []byte(""), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "nil-wrapper", @@ -77,7 +77,7 @@ func TestRepository_CreateOplogKey(t *testing.T) { keyWrapper: nil, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "not-rkv-wrapper", @@ -87,7 +87,7 @@ func TestRepository_CreateOplogKey(t *testing.T) { keyWrapper: wrapper, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "wrapper-missing-id", @@ -104,7 +104,7 @@ func TestRepository_CreateOplogKey(t *testing.T) { }(), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -128,7 +128,7 @@ func TestRepository_CreateOplogKey(t *testing.T) { // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, opk.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) assert.NotNil(opv.CreateTime) foundKeyVersion, err := repo.LookupOplogKeyVersion(context.Background(), tt.args.keyWrapper, opv.PrivateId) @@ -138,7 +138,7 @@ func TestRepository_CreateOplogKey(t *testing.T) { // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, opv.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) }) } } @@ -183,7 +183,7 @@ func TestRepository_DeleteOplogKey(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "not-found", @@ -199,7 +199,7 @@ func TestRepository_DeleteOplogKey(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrRecordNotFound, + wantIsError: errors.ErrRecordNotFound, }, } for _, tt := range tests { @@ -215,7 +215,7 @@ func TestRepository_DeleteOplogKey(t *testing.T) { // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) @@ -223,12 +223,12 @@ func TestRepository_DeleteOplogKey(t *testing.T) { foundKey, err := repo.LookupOplogKey(context.Background(), tt.args.key.PrivateId) assert.Error(err) assert.Nil(foundKey) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/kms/repository_oplog_key_version.go b/internal/kms/repository_oplog_key_version.go index 324031685..92c40c945 100644 --- a/internal/kms/repository_oplog_key_version.go +++ b/internal/kms/repository_oplog_key_version.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" wrapping "github.com/hashicorp/go-kms-wrapping" ) @@ -13,20 +14,20 @@ import ( // version with its PrivateId. There are no valid options at this time. func (r *Repository) CreateOplogKeyVersion(ctx context.Context, rkvWrapper wrapping.Wrapper, oplogKeyId string, key []byte, opt ...Option) (*OplogKeyVersion, error) { if rkvWrapper == nil { - return nil, fmt.Errorf("create oplog key version: missing root key version wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create oplog key version: missing root key version wrapper: %w", errors.ErrInvalidParameter) } rootKeyVersionId := rkvWrapper.KeyID() switch { case !strings.HasPrefix(rootKeyVersionId, RootKeyVersionPrefix): - return nil, fmt.Errorf("create oplog key version: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, db.ErrInvalidParameter) + return nil, fmt.Errorf("create oplog key version: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, errors.ErrInvalidParameter) case rootKeyVersionId == "": - return nil, fmt.Errorf("create oplog key version: missing root key version id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create oplog key version: missing root key version id: %w", errors.ErrInvalidParameter) } if oplogKeyId == "" { - return nil, fmt.Errorf("create oplog key version: missing oplog key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create oplog key version: missing oplog key id: %w", errors.ErrInvalidParameter) } if len(key) == 0 { - return nil, fmt.Errorf("create oplog key version: missing key: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create oplog key version: missing key: %w", errors.ErrInvalidParameter) } kv := AllocOplogKeyVersion() id, err := newOplogKeyVersionId() @@ -65,10 +66,10 @@ func (r *Repository) CreateOplogKeyVersion(ctx context.Context, rkvWrapper wrapp // the key version is not found, it will return nil, nil. func (r *Repository) LookupOplogKeyVersion(ctx context.Context, keyWrapper wrapping.Wrapper, privateId string, opt ...Option) (*OplogKeyVersion, error) { if privateId == "" { - return nil, fmt.Errorf("lookup oplog key version: missing private id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup oplog key version: missing private id: %w", errors.ErrInvalidParameter) } if keyWrapper == nil { - return nil, fmt.Errorf("lookup oplog key version: missing key wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup oplog key version: missing key wrapper: %w", errors.ErrInvalidParameter) } k := AllocOplogKeyVersion() k.PrivateId = privateId @@ -86,7 +87,7 @@ func (r *Repository) LookupOplogKeyVersion(ctx context.Context, keyWrapper wrapp // are ignored. func (r *Repository) DeleteOplogKeyVersion(ctx context.Context, privateId string, opt ...Option) (int, error) { if privateId == "" { - return db.NoRowsAffected, fmt.Errorf("delete oplog key version: missing private id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete oplog key version: missing private id: %w", errors.ErrInvalidParameter) } k := AllocOplogKeyVersion() k.PrivateId = privateId @@ -104,7 +105,7 @@ func (r *Repository) DeleteOplogKeyVersion(ctx context.Context, privateId string // no oplog entries for the key version rowsDeleted, err = w.Delete(ctx, dk) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, @@ -117,20 +118,20 @@ func (r *Repository) DeleteOplogKeyVersion(ctx context.Context, privateId string // LatestOplogKeyVersion searches for the key version with the highest // version number. When no results are found, it returns nil, -// db.ErrRecordNotFound. +// errors.ErrRecordNotFound. func (r *Repository) LatestOplogKeyVersion(ctx context.Context, rkvWrapper wrapping.Wrapper, oplogKeyId string, opt ...Option) (*OplogKeyVersion, error) { if oplogKeyId == "" { - return nil, fmt.Errorf("latest oplog key version: missing oplog key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("latest oplog key version: missing oplog key id: %w", errors.ErrInvalidParameter) } if rkvWrapper == nil { - return nil, fmt.Errorf("latest oplog key version: missing root key version wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("latest oplog key version: missing root key version wrapper: %w", errors.ErrInvalidParameter) } var foundKeys []*OplogKeyVersion if err := r.reader.SearchWhere(ctx, &foundKeys, "oplog_key_id = ?", []interface{}{oplogKeyId}, db.WithLimit(1), db.WithOrder("version desc")); err != nil { return nil, fmt.Errorf("latest oplog key version: failed %w for %s", err, oplogKeyId) } if len(foundKeys) == 0 { - return nil, db.ErrRecordNotFound + return nil, errors.ErrRecordNotFound } if err := foundKeys[0].Decrypt(ctx, rkvWrapper); err != nil { return nil, fmt.Errorf("latest oplog key version: %w", err) @@ -141,10 +142,10 @@ func (r *Repository) LatestOplogKeyVersion(ctx context.Context, rkvWrapper wrapp // ListOplogKeyVersions will lists versions of a key. Supports the WithLimit option. func (r *Repository) ListOplogKeyVersions(ctx context.Context, rkvWrapper wrapping.Wrapper, oplogKeyId string, opt ...Option) ([]DekVersion, error) { if oplogKeyId == "" { - return nil, fmt.Errorf("list oplog key versions: missing oplog key id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list oplog key versions: missing oplog key id %w", errors.ErrInvalidParameter) } if rkvWrapper == nil { - return nil, fmt.Errorf("list oplog key versions: missing root key version wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list oplog key versions: missing root key version wrapper: %w", errors.ErrInvalidParameter) } var versions []*OplogKeyVersion err := r.list(ctx, &versions, "oplog_key_id = ?", []interface{}{oplogKeyId}, opt...) diff --git a/internal/kms/repository_oplog_key_version_test.go b/internal/kms/repository_oplog_key_version_test.go index 088009f11..03e828eb3 100644 --- a/internal/kms/repository_oplog_key_version_test.go +++ b/internal/kms/repository_oplog_key_version_test.go @@ -2,11 +2,11 @@ package kms_test import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -67,7 +67,7 @@ func TestRepository_CreateOplogKeyVersion(t *testing.T) { oplogKeyId: dk.PrivateId, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "nil-wrapper", @@ -76,7 +76,7 @@ func TestRepository_CreateOplogKeyVersion(t *testing.T) { keyWrapper: nil, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -100,7 +100,7 @@ func TestRepository_CreateOplogKeyVersion(t *testing.T) { // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, k.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } @@ -147,7 +147,7 @@ func TestRepository_DeleteOplogKeyVersion(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "not-found", @@ -163,7 +163,7 @@ func TestRepository_DeleteOplogKeyVersion(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrRecordNotFound, + wantIsError: errors.ErrRecordNotFound, }, } for _, tt := range tests { @@ -178,7 +178,7 @@ func TestRepository_DeleteOplogKeyVersion(t *testing.T) { } err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) @@ -186,12 +186,12 @@ func TestRepository_DeleteOplogKeyVersion(t *testing.T) { foundKey, err := repo.LookupOplogKeyVersion(context.Background(), wrapper, tt.args.key.PrivateId) assert.Error(err) assert.Nil(foundKey) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } @@ -236,14 +236,14 @@ func TestRepository_LatestOplogKeyVersion(t *testing.T) { createCnt: 0, keyWrapper: rkvWrapper, wantErr: true, - wantIsError: db.ErrRecordNotFound, + wantIsError: errors.ErrRecordNotFound, }, { name: "nil-wrapper", createCnt: 5, keyWrapper: nil, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { diff --git a/internal/kms/repository_root_key.go b/internal/kms/repository_root_key.go index 642c08d9f..6d396e4a4 100644 --- a/internal/kms/repository_root_key.go +++ b/internal/kms/repository_root_key.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" wrapping "github.com/hashicorp/go-kms-wrapping" ) @@ -35,13 +36,13 @@ func (r *Repository) CreateRootKey(ctx context.Context, keyWrapper wrapping.Wrap // a db.TxHandler and allows this capability to be shared with the iam repo. func createRootKeyTx(ctx context.Context, w db.Writer, keyWrapper wrapping.Wrapper, scopeId string, key []byte) (*RootKey, *RootKeyVersion, error) { if scopeId == "" { - return nil, nil, fmt.Errorf("create root key: missing scope id: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create root key: missing scope id: %w", errors.ErrInvalidParameter) } if keyWrapper == nil { - return nil, nil, fmt.Errorf("create root key: missing key wrapper: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create root key: missing key wrapper: %w", errors.ErrInvalidParameter) } if len(key) == 0 { - return nil, nil, fmt.Errorf("create root key: missing key: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create root key: missing key: %w", errors.ErrInvalidParameter) } rk := AllocRootKey() kv := AllocRootKeyVersion() @@ -79,10 +80,10 @@ func createRootKeyTx(ctx context.Context, w db.Writer, keyWrapper wrapping.Wrapp // found, it will return nil, nil. func (r *Repository) LookupRootKey(ctx context.Context, keyWrapper wrapping.Wrapper, privateId string, opt ...Option) (*RootKey, error) { if privateId == "" { - return nil, fmt.Errorf("lookup root key: missing private id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup root key: missing private id: %w", errors.ErrInvalidParameter) } if keyWrapper == nil { - return nil, fmt.Errorf("lookup root key: missing key wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup root key: missing key wrapper: %w", errors.ErrInvalidParameter) } k := AllocRootKey() k.PrivateId = privateId @@ -97,7 +98,7 @@ func (r *Repository) LookupRootKey(ctx context.Context, keyWrapper wrapping.Wrap // are ignored. func (r *Repository) DeleteRootKey(ctx context.Context, privateId string, opt ...Option) (int, error) { if privateId == "" { - return db.NoRowsAffected, fmt.Errorf("delete root key: missing private id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete root key: missing private id: %w", errors.ErrInvalidParameter) } k := AllocRootKey() k.PrivateId = privateId @@ -115,7 +116,7 @@ func (r *Repository) DeleteRootKey(ctx context.Context, privateId string, opt .. // no oplog entries for root keys rowsDeleted, err = w.Delete(ctx, dk) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, diff --git a/internal/kms/repository_root_key_test.go b/internal/kms/repository_root_key_test.go index 92b4f65c4..22f747ada 100644 --- a/internal/kms/repository_root_key_test.go +++ b/internal/kms/repository_root_key_test.go @@ -2,11 +2,11 @@ package kms_test import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -72,7 +72,7 @@ func TestRepository_CreateRootKey(t *testing.T) { keyWrapper: wrapper, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "nil-wrapper", @@ -82,7 +82,7 @@ func TestRepository_CreateRootKey(t *testing.T) { keyWrapper: nil, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -106,7 +106,7 @@ func TestRepository_CreateRootKey(t *testing.T) { // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, rk.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) assert.NotNil(kv.CreateTime) foundKeyVersion, err := repo.LookupRootKeyVersion(context.Background(), tt.args.keyWrapper, kv.PrivateId) @@ -116,7 +116,7 @@ func TestRepository_CreateRootKey(t *testing.T) { // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, kv.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) }) } } @@ -160,7 +160,7 @@ func TestRepository_DeleteRootKey(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "not-found", @@ -176,7 +176,7 @@ func TestRepository_DeleteRootKey(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrRecordNotFound, + wantIsError: errors.ErrRecordNotFound, }, } for _, tt := range tests { @@ -192,7 +192,7 @@ func TestRepository_DeleteRootKey(t *testing.T) { // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) @@ -200,12 +200,12 @@ func TestRepository_DeleteRootKey(t *testing.T) { foundKey, err := repo.LookupRootKey(context.Background(), wrapper, tt.args.key.PrivateId) assert.Error(err) assert.Nil(foundKey) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/kms/repository_root_key_version.go b/internal/kms/repository_root_key_version.go index ec46838c9..3d98226e5 100644 --- a/internal/kms/repository_root_key_version.go +++ b/internal/kms/repository_root_key_version.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" wrapping "github.com/hashicorp/go-kms-wrapping" ) @@ -12,13 +13,13 @@ import ( // version with its PrivateId. There are no valid options at this time. func (r *Repository) CreateRootKeyVersion(ctx context.Context, keyWrapper wrapping.Wrapper, rootKeyId string, key []byte, opt ...Option) (*RootKeyVersion, error) { if rootKeyId == "" { - return nil, fmt.Errorf("create root key version: missing root key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create root key version: missing root key id: %w", errors.ErrInvalidParameter) } if keyWrapper == nil { - return nil, fmt.Errorf("create root key version: missing key wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create root key version: missing key wrapper: %w", errors.ErrInvalidParameter) } if len(key) == 0 { - return nil, fmt.Errorf("create root key version: missing key: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create root key version: missing key: %w", errors.ErrInvalidParameter) } kv := AllocRootKeyVersion() id, err := newRootKeyVersionId() @@ -56,10 +57,10 @@ func (r *Repository) CreateRootKeyVersion(ctx context.Context, keyWrapper wrappi // the key version is not found, it will return nil, nil. func (r *Repository) LookupRootKeyVersion(ctx context.Context, keyWrapper wrapping.Wrapper, privateId string, opt ...Option) (*RootKeyVersion, error) { if privateId == "" { - return nil, fmt.Errorf("lookup root key version: missing private id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup root key version: missing private id: %w", errors.ErrInvalidParameter) } if keyWrapper == nil { - return nil, fmt.Errorf("lookup root key version: missing key wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup root key version: missing key wrapper: %w", errors.ErrInvalidParameter) } k := AllocRootKeyVersion() k.PrivateId = privateId @@ -77,7 +78,7 @@ func (r *Repository) LookupRootKeyVersion(ctx context.Context, keyWrapper wrappi // are ignored. func (r *Repository) DeleteRootKeyVersion(ctx context.Context, privateId string, opt ...Option) (int, error) { if privateId == "" { - return db.NoRowsAffected, fmt.Errorf("delete root key version: missing private id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete root key version: missing private id: %w", errors.ErrInvalidParameter) } k := AllocRootKeyVersion() k.PrivateId = privateId @@ -95,7 +96,7 @@ func (r *Repository) DeleteRootKeyVersion(ctx context.Context, privateId string, // no oplog entries for root key version rowsDeleted, err = w.Delete(ctx, dk) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, @@ -108,20 +109,20 @@ func (r *Repository) DeleteRootKeyVersion(ctx context.Context, privateId string, // LatestRootKeyVersion searches for the root key version with the highest // version number. When no results are found, it returns nil, -// db.ErrRecordNotFound. +// errors.ErrRecordNotFound. func (r *Repository) LatestRootKeyVersion(ctx context.Context, keyWrapper wrapping.Wrapper, rootKeyId string, opt ...Option) (*RootKeyVersion, error) { if rootKeyId == "" { - return nil, fmt.Errorf("latest root key version: missing root key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("latest root key version: missing root key id: %w", errors.ErrInvalidParameter) } if keyWrapper == nil { - return nil, fmt.Errorf("latest root key version: missing key wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("latest root key version: missing key wrapper: %w", errors.ErrInvalidParameter) } var foundKeys []RootKeyVersion if err := r.reader.SearchWhere(ctx, &foundKeys, "root_key_id = ?", []interface{}{rootKeyId}, db.WithLimit(1), db.WithOrder("version desc")); err != nil { return nil, fmt.Errorf("latest root key version: failed %w for %s", err, rootKeyId) } if len(foundKeys) == 0 { - return nil, db.ErrRecordNotFound + return nil, errors.ErrRecordNotFound } if err := foundKeys[0].Decrypt(ctx, keyWrapper); err != nil { return nil, fmt.Errorf("latest root key version: %w", err) @@ -132,10 +133,10 @@ func (r *Repository) LatestRootKeyVersion(ctx context.Context, keyWrapper wrappi // ListRootKeyVersions in versions of a root key. Supports the WithLimit option. func (r *Repository) ListRootKeyVersions(ctx context.Context, keyWrapper wrapping.Wrapper, rootKeyId string, opt ...Option) ([]*RootKeyVersion, error) { if rootKeyId == "" { - return nil, fmt.Errorf("list root key versions: missing root key id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list root key versions: missing root key id %w", errors.ErrInvalidParameter) } if keyWrapper == nil { - return nil, fmt.Errorf("list root key versions: missing key wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list root key versions: missing key wrapper: %w", errors.ErrInvalidParameter) } var versions []*RootKeyVersion err := r.list(ctx, &versions, "root_key_id = ?", []interface{}{rootKeyId}, opt...) diff --git a/internal/kms/repository_root_key_version_test.go b/internal/kms/repository_root_key_version_test.go index 4375f6ebf..2f1a16b07 100644 --- a/internal/kms/repository_root_key_version_test.go +++ b/internal/kms/repository_root_key_version_test.go @@ -2,11 +2,11 @@ package kms_test import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -65,7 +65,7 @@ func TestRepository_CreateRootKeyVersion(t *testing.T) { keyWrapper: wrapper, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "nil-wrapper", @@ -75,7 +75,7 @@ func TestRepository_CreateRootKeyVersion(t *testing.T) { keyWrapper: nil, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -99,7 +99,7 @@ func TestRepository_CreateRootKeyVersion(t *testing.T) { // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, k.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } @@ -147,7 +147,7 @@ func TestRepository_DeleteRootKeyVersion(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "not-found", @@ -163,7 +163,7 @@ func TestRepository_DeleteRootKeyVersion(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrRecordNotFound, + wantIsError: errors.ErrRecordNotFound, }, } for _, tt := range tests { @@ -178,7 +178,7 @@ func TestRepository_DeleteRootKeyVersion(t *testing.T) { } err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) @@ -186,12 +186,12 @@ func TestRepository_DeleteRootKeyVersion(t *testing.T) { foundKey, err := repo.LookupRootKeyVersion(context.Background(), wrapper, tt.args.key.PrivateId) assert.Error(err) assert.Nil(foundKey) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } @@ -234,14 +234,14 @@ func TestRepository_LatestRootKeyVersion(t *testing.T) { createCnt: 0, keyWrapper: wrapper, wantErr: true, - wantIsError: db.ErrRecordNotFound, + wantIsError: errors.ErrRecordNotFound, }, { name: "nil-wrapper", createCnt: 5, keyWrapper: nil, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { diff --git a/internal/kms/repository_session_key.go b/internal/kms/repository_session_key.go index 4569b5abd..a3837a4cf 100644 --- a/internal/kms/repository_session_key.go +++ b/internal/kms/repository_session_key.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" wrapping "github.com/hashicorp/go-kms-wrapping" ) @@ -36,17 +37,17 @@ func (r *Repository) CreateSessionKey(ctx context.Context, rkvWrapper wrapping.W // a db.TxHandler and allows this capability to be shared with the iam repo. func createSessionKeyTx(ctx context.Context, r db.Reader, w db.Writer, rkvWrapper wrapping.Wrapper, key []byte) (*SessionKey, *SessionKeyVersion, error) { if rkvWrapper == nil { - return nil, nil, fmt.Errorf("create session key: missing key wrapper: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session key: missing key wrapper: %w", errors.ErrInvalidParameter) } if len(key) == 0 { - return nil, nil, fmt.Errorf("create session key: missing key: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session key: missing key: %w", errors.ErrInvalidParameter) } rootKeyVersionId := rkvWrapper.KeyID() switch { case !strings.HasPrefix(rootKeyVersionId, RootKeyVersionPrefix): - return nil, nil, fmt.Errorf("create session key: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session key: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, errors.ErrInvalidParameter) case rootKeyVersionId == "": - return nil, nil, fmt.Errorf("create session key: missing root key version id: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session key: missing root key version id: %w", errors.ErrInvalidParameter) } rv := AllocRootKeyVersion() rv.PrivateId = rootKeyVersionId @@ -92,7 +93,7 @@ func createSessionKeyTx(ctx context.Context, r db.Reader, w db.Writer, rkvWrappe // found, it will return nil, nil. func (r *Repository) LookupSessionKey(ctx context.Context, privateId string, opt ...Option) (*SessionKey, error) { if privateId == "" { - return nil, fmt.Errorf("lookup session key: missing private id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup session key: missing private id: %w", errors.ErrInvalidParameter) } k := AllocSessionKey() k.PrivateId = privateId @@ -107,7 +108,7 @@ func (r *Repository) LookupSessionKey(ctx context.Context, privateId string, opt // are ignored. func (r *Repository) DeleteSessionKey(ctx context.Context, privateId string, opt ...Option) (int, error) { if privateId == "" { - return db.NoRowsAffected, fmt.Errorf("delete session key: missing private id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete session key: missing private id: %w", errors.ErrInvalidParameter) } k := AllocSessionKey() k.PrivateId = privateId @@ -125,7 +126,7 @@ func (r *Repository) DeleteSessionKey(ctx context.Context, privateId string, opt // no session entries for root keys rowsDeleted, err = w.Delete(ctx, dk) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, diff --git a/internal/kms/repository_session_key_test.go b/internal/kms/repository_session_key_test.go index 3fbe710b9..a63ad2fd4 100644 --- a/internal/kms/repository_session_key_test.go +++ b/internal/kms/repository_session_key_test.go @@ -2,11 +2,11 @@ package kms_test import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -57,7 +57,7 @@ func TestRepository_CreateSessionKey(t *testing.T) { keyWrapper: rkvWrapper, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-key", @@ -67,7 +67,7 @@ func TestRepository_CreateSessionKey(t *testing.T) { key: []byte(""), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "nil-wrapper", @@ -77,7 +77,7 @@ func TestRepository_CreateSessionKey(t *testing.T) { keyWrapper: nil, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "not-rkv-wrapper", @@ -87,7 +87,7 @@ func TestRepository_CreateSessionKey(t *testing.T) { keyWrapper: wrapper, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "wrapper-missing-id", @@ -104,7 +104,7 @@ func TestRepository_CreateSessionKey(t *testing.T) { }(), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -128,7 +128,7 @@ func TestRepository_CreateSessionKey(t *testing.T) { // make sure there was no session written err = db.TestVerifyOplog(t, rw, tk.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) assert.NotNil(tv.CreateTime) foundKeyVersion, err := repo.LookupSessionKeyVersion(context.Background(), tt.args.keyWrapper, tv.PrivateId) @@ -138,7 +138,7 @@ func TestRepository_CreateSessionKey(t *testing.T) { // make sure there was no session written err = db.TestVerifyOplog(t, rw, tv.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) }) } } @@ -183,7 +183,7 @@ func TestRepository_DeleteSessionKey(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "not-found", @@ -199,7 +199,7 @@ func TestRepository_DeleteSessionKey(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrRecordNotFound, + wantIsError: errors.ErrRecordNotFound, }, } for _, tt := range tests { @@ -215,7 +215,7 @@ func TestRepository_DeleteSessionKey(t *testing.T) { // make sure there was no session written err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) @@ -223,12 +223,12 @@ func TestRepository_DeleteSessionKey(t *testing.T) { foundKey, err := repo.LookupSessionKey(context.Background(), tt.args.key.PrivateId) assert.Error(err) assert.Nil(foundKey) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) // make sure there was no session written err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/kms/repository_session_key_version.go b/internal/kms/repository_session_key_version.go index c09756588..45838ba36 100644 --- a/internal/kms/repository_session_key_version.go +++ b/internal/kms/repository_session_key_version.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" wrapping "github.com/hashicorp/go-kms-wrapping" ) @@ -13,20 +14,20 @@ import ( // version with its PrivateId. There are no valid options at this time. func (r *Repository) CreateSessionKeyVersion(ctx context.Context, rkvWrapper wrapping.Wrapper, sessionKeyId string, key []byte, opt ...Option) (*SessionKeyVersion, error) { if rkvWrapper == nil { - return nil, fmt.Errorf("create session key version: missing root key version wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create session key version: missing root key version wrapper: %w", errors.ErrInvalidParameter) } rootKeyVersionId := rkvWrapper.KeyID() switch { case !strings.HasPrefix(rootKeyVersionId, RootKeyVersionPrefix): - return nil, fmt.Errorf("create session key version: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, db.ErrInvalidParameter) + return nil, fmt.Errorf("create session key version: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, errors.ErrInvalidParameter) case rootKeyVersionId == "": - return nil, fmt.Errorf("create session key version: missing root key version id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create session key version: missing root key version id: %w", errors.ErrInvalidParameter) } if sessionKeyId == "" { - return nil, fmt.Errorf("create session key version: missing session key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create session key version: missing session key id: %w", errors.ErrInvalidParameter) } if len(key) == 0 { - return nil, fmt.Errorf("create session key version: missing key: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create session key version: missing key: %w", errors.ErrInvalidParameter) } kv := AllocSessionKeyVersion() id, err := newSessionKeyVersionId() @@ -65,10 +66,10 @@ func (r *Repository) CreateSessionKeyVersion(ctx context.Context, rkvWrapper wra // the key version is not found, it will return nil, nil. func (r *Repository) LookupSessionKeyVersion(ctx context.Context, keyWrapper wrapping.Wrapper, privateId string, opt ...Option) (*SessionKeyVersion, error) { if privateId == "" { - return nil, fmt.Errorf("lookup session key version: missing private id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup session key version: missing private id: %w", errors.ErrInvalidParameter) } if keyWrapper == nil { - return nil, fmt.Errorf("lookup session key version: missing key wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup session key version: missing key wrapper: %w", errors.ErrInvalidParameter) } k := AllocSessionKeyVersion() k.PrivateId = privateId @@ -86,7 +87,7 @@ func (r *Repository) LookupSessionKeyVersion(ctx context.Context, keyWrapper wra // are ignored. func (r *Repository) DeleteSessionKeyVersion(ctx context.Context, privateId string, opt ...Option) (int, error) { if privateId == "" { - return db.NoRowsAffected, fmt.Errorf("delete session key version: missing private id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete session key version: missing private id: %w", errors.ErrInvalidParameter) } k := AllocSessionKeyVersion() k.PrivateId = privateId @@ -104,7 +105,7 @@ func (r *Repository) DeleteSessionKeyVersion(ctx context.Context, privateId stri // no session entries for the key version rowsDeleted, err = w.Delete(ctx, dk) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, @@ -117,20 +118,20 @@ func (r *Repository) DeleteSessionKeyVersion(ctx context.Context, privateId stri // LatestSessionKeyVersion searches for the key version with the highest // version number. When no results are found, it returns nil, -// db.ErrRecordNotFound. +// errors.ErrRecordNotFound. func (r *Repository) LatestSessionKeyVersion(ctx context.Context, rkvWrapper wrapping.Wrapper, sessionKeyId string, opt ...Option) (*SessionKeyVersion, error) { if sessionKeyId == "" { - return nil, fmt.Errorf("latest session key version: missing session key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("latest session key version: missing session key id: %w", errors.ErrInvalidParameter) } if rkvWrapper == nil { - return nil, fmt.Errorf("latest session key version: missing root key version wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("latest session key version: missing root key version wrapper: %w", errors.ErrInvalidParameter) } var foundKeys []*SessionKeyVersion if err := r.reader.SearchWhere(ctx, &foundKeys, "session_key_id = ?", []interface{}{sessionKeyId}, db.WithLimit(1), db.WithOrder("version desc")); err != nil { return nil, fmt.Errorf("latest session key version: failed %w for %s", err, sessionKeyId) } if len(foundKeys) == 0 { - return nil, db.ErrRecordNotFound + return nil, errors.ErrRecordNotFound } if err := foundKeys[0].Decrypt(ctx, rkvWrapper); err != nil { return nil, fmt.Errorf("latest session key version: %w", err) @@ -141,10 +142,10 @@ func (r *Repository) LatestSessionKeyVersion(ctx context.Context, rkvWrapper wra // ListSessionKeyVersions will lists versions of a key. Supports the WithLimit option. func (r *Repository) ListSessionKeyVersions(ctx context.Context, rkvWrapper wrapping.Wrapper, sessionKeyId string, opt ...Option) ([]DekVersion, error) { if sessionKeyId == "" { - return nil, fmt.Errorf("list session key versions: missing session key id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list session key versions: missing session key id %w", errors.ErrInvalidParameter) } if rkvWrapper == nil { - return nil, fmt.Errorf("list session key versions: missing root key version wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list session key versions: missing root key version wrapper: %w", errors.ErrInvalidParameter) } var versions []*SessionKeyVersion err := r.list(ctx, &versions, "session_key_id = ?", []interface{}{sessionKeyId}, opt...) diff --git a/internal/kms/repository_session_key_version_test.go b/internal/kms/repository_session_key_version_test.go index 764af7f51..cb808e886 100644 --- a/internal/kms/repository_session_key_version_test.go +++ b/internal/kms/repository_session_key_version_test.go @@ -2,11 +2,11 @@ package kms_test import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -67,7 +67,7 @@ func TestRepository_CreateSessionKeyVersion(t *testing.T) { sessionKeyId: sk.PrivateId, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "nil-wrapper", @@ -76,7 +76,7 @@ func TestRepository_CreateSessionKeyVersion(t *testing.T) { keyWrapper: nil, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -100,7 +100,7 @@ func TestRepository_CreateSessionKeyVersion(t *testing.T) { // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, k.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } @@ -147,7 +147,7 @@ func TestRepository_DeleteSessionKeyVersion(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "not-found", @@ -163,7 +163,7 @@ func TestRepository_DeleteSessionKeyVersion(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrRecordNotFound, + wantIsError: errors.ErrRecordNotFound, }, } for _, tt := range tests { @@ -178,7 +178,7 @@ func TestRepository_DeleteSessionKeyVersion(t *testing.T) { } err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) @@ -186,12 +186,12 @@ func TestRepository_DeleteSessionKeyVersion(t *testing.T) { foundKey, err := repo.LookupSessionKeyVersion(context.Background(), wrapper, tt.args.key.PrivateId) assert.Error(err) assert.Nil(foundKey) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } @@ -236,14 +236,14 @@ func TestRepository_LatestSessionKeyVersion(t *testing.T) { createCnt: 0, keyWrapper: rkvWrapper, wantErr: true, - wantIsError: db.ErrRecordNotFound, + wantIsError: errors.ErrRecordNotFound, }, { name: "nil-wrapper", createCnt: 5, keyWrapper: nil, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { diff --git a/internal/kms/repository_test.go b/internal/kms/repository_test.go index 1f9be0ba4..1380513a8 100644 --- a/internal/kms/repository_test.go +++ b/internal/kms/repository_test.go @@ -3,11 +3,11 @@ package kms_test import ( "context" "crypto/rand" - "errors" "io" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" wrapping "github.com/hashicorp/go-kms-wrapping" @@ -121,7 +121,7 @@ func TestCreateKeysTx(t *testing.T) { scopeId: org.PublicId, }, wantErr: true, - wantErrIs: db.ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "nil-writer", @@ -133,7 +133,7 @@ func TestCreateKeysTx(t *testing.T) { scopeId: org.PublicId, }, wantErr: true, - wantErrIs: db.ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "nil-wrapper", @@ -145,7 +145,7 @@ func TestCreateKeysTx(t *testing.T) { scopeId: org.PublicId, }, wantErr: true, - wantErrIs: db.ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "empty-scope", @@ -157,7 +157,7 @@ func TestCreateKeysTx(t *testing.T) { scopeId: "", }, wantErr: true, - wantErrIs: db.ErrInvalidParameter, + wantErrIs: errors.ErrInvalidParameter, }, { name: "bad-scope", diff --git a/internal/kms/repository_token_key.go b/internal/kms/repository_token_key.go index 814970b8a..d7667f629 100644 --- a/internal/kms/repository_token_key.go +++ b/internal/kms/repository_token_key.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" wrapping "github.com/hashicorp/go-kms-wrapping" ) @@ -36,17 +37,17 @@ func (r *Repository) CreateTokenKey(ctx context.Context, rkvWrapper wrapping.Wra // a db.TxHandler and allows this capability to be shared with the iam repo. func createTokenKeyTx(ctx context.Context, r db.Reader, w db.Writer, rkvWrapper wrapping.Wrapper, key []byte) (*TokenKey, *TokenKeyVersion, error) { if rkvWrapper == nil { - return nil, nil, fmt.Errorf("create token key: missing key wrapper: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create token key: missing key wrapper: %w", errors.ErrInvalidParameter) } if len(key) == 0 { - return nil, nil, fmt.Errorf("create token key: missing key: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create token key: missing key: %w", errors.ErrInvalidParameter) } rootKeyVersionId := rkvWrapper.KeyID() switch { case !strings.HasPrefix(rootKeyVersionId, RootKeyVersionPrefix): - return nil, nil, fmt.Errorf("create token key: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create token key: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, errors.ErrInvalidParameter) case rootKeyVersionId == "": - return nil, nil, fmt.Errorf("create token key: missing root key version id: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create token key: missing root key version id: %w", errors.ErrInvalidParameter) } rv := AllocRootKeyVersion() rv.PrivateId = rootKeyVersionId @@ -92,7 +93,7 @@ func createTokenKeyTx(ctx context.Context, r db.Reader, w db.Writer, rkvWrapper // found, it will return nil, nil. func (r *Repository) LookupTokenKey(ctx context.Context, privateId string, opt ...Option) (*TokenKey, error) { if privateId == "" { - return nil, fmt.Errorf("lookup token key: missing private id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup token key: missing private id: %w", errors.ErrInvalidParameter) } k := AllocTokenKey() k.PrivateId = privateId @@ -107,7 +108,7 @@ func (r *Repository) LookupTokenKey(ctx context.Context, privateId string, opt . // are ignored. func (r *Repository) DeleteTokenKey(ctx context.Context, privateId string, opt ...Option) (int, error) { if privateId == "" { - return db.NoRowsAffected, fmt.Errorf("delete token key: missing private id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete token key: missing private id: %w", errors.ErrInvalidParameter) } k := AllocTokenKey() k.PrivateId = privateId @@ -125,7 +126,7 @@ func (r *Repository) DeleteTokenKey(ctx context.Context, privateId string, opt . // no token entries for root keys rowsDeleted, err = w.Delete(ctx, dk) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, diff --git a/internal/kms/repository_token_key_test.go b/internal/kms/repository_token_key_test.go index 343eb8cb9..734e89b87 100644 --- a/internal/kms/repository_token_key_test.go +++ b/internal/kms/repository_token_key_test.go @@ -2,11 +2,11 @@ package kms_test import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -57,7 +57,7 @@ func TestRepository_CreateTokenKey(t *testing.T) { keyWrapper: rkvWrapper, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-key", @@ -67,7 +67,7 @@ func TestRepository_CreateTokenKey(t *testing.T) { key: []byte(""), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "nil-wrapper", @@ -77,7 +77,7 @@ func TestRepository_CreateTokenKey(t *testing.T) { keyWrapper: nil, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "not-rkv-wrapper", @@ -87,7 +87,7 @@ func TestRepository_CreateTokenKey(t *testing.T) { keyWrapper: wrapper, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "wrapper-missing-id", @@ -104,7 +104,7 @@ func TestRepository_CreateTokenKey(t *testing.T) { }(), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -128,7 +128,7 @@ func TestRepository_CreateTokenKey(t *testing.T) { // make sure there was no token written err = db.TestVerifyOplog(t, rw, tk.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) assert.NotNil(tv.CreateTime) foundKeyVersion, err := repo.LookupTokenKeyVersion(context.Background(), tt.args.keyWrapper, tv.PrivateId) @@ -138,7 +138,7 @@ func TestRepository_CreateTokenKey(t *testing.T) { // make sure there was no token written err = db.TestVerifyOplog(t, rw, tv.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) }) } } @@ -183,7 +183,7 @@ func TestRepository_DeleteTokenKey(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "not-found", @@ -199,7 +199,7 @@ func TestRepository_DeleteTokenKey(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrRecordNotFound, + wantIsError: errors.ErrRecordNotFound, }, } for _, tt := range tests { @@ -215,7 +215,7 @@ func TestRepository_DeleteTokenKey(t *testing.T) { // make sure there was no token written err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) @@ -223,12 +223,12 @@ func TestRepository_DeleteTokenKey(t *testing.T) { foundKey, err := repo.LookupTokenKey(context.Background(), tt.args.key.PrivateId) assert.Error(err) assert.Nil(foundKey) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) // make sure there was no token written err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/kms/repository_token_key_version.go b/internal/kms/repository_token_key_version.go index 4f1e63867..8038ba576 100644 --- a/internal/kms/repository_token_key_version.go +++ b/internal/kms/repository_token_key_version.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" wrapping "github.com/hashicorp/go-kms-wrapping" ) @@ -13,20 +14,20 @@ import ( // version with its PrivateId. There are no valid options at this time. func (r *Repository) CreateTokenKeyVersion(ctx context.Context, rkvWrapper wrapping.Wrapper, tokenKeyId string, key []byte, opt ...Option) (*TokenKeyVersion, error) { if rkvWrapper == nil { - return nil, fmt.Errorf("create token key version: missing root key version wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create token key version: missing root key version wrapper: %w", errors.ErrInvalidParameter) } rootKeyVersionId := rkvWrapper.KeyID() switch { case !strings.HasPrefix(rootKeyVersionId, RootKeyVersionPrefix): - return nil, fmt.Errorf("create token key version: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, db.ErrInvalidParameter) + return nil, fmt.Errorf("create token key version: root key version id %s doesn't start with prefix %s: %w", rootKeyVersionId, RootKeyVersionPrefix, errors.ErrInvalidParameter) case rootKeyVersionId == "": - return nil, fmt.Errorf("create token key version: missing root key version id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create token key version: missing root key version id: %w", errors.ErrInvalidParameter) } if tokenKeyId == "" { - return nil, fmt.Errorf("create token key version: missing token key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create token key version: missing token key id: %w", errors.ErrInvalidParameter) } if len(key) == 0 { - return nil, fmt.Errorf("create token key version: missing key: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("create token key version: missing key: %w", errors.ErrInvalidParameter) } kv := AllocTokenKeyVersion() id, err := newTokenKeyVersionId() @@ -65,10 +66,10 @@ func (r *Repository) CreateTokenKeyVersion(ctx context.Context, rkvWrapper wrapp // the key version is not found, it will return nil, nil. func (r *Repository) LookupTokenKeyVersion(ctx context.Context, keyWrapper wrapping.Wrapper, privateId string, opt ...Option) (*TokenKeyVersion, error) { if privateId == "" { - return nil, fmt.Errorf("lookup token key version: missing private id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup token key version: missing private id: %w", errors.ErrInvalidParameter) } if keyWrapper == nil { - return nil, fmt.Errorf("lookup token key version: missing key wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("lookup token key version: missing key wrapper: %w", errors.ErrInvalidParameter) } k := AllocTokenKeyVersion() k.PrivateId = privateId @@ -86,7 +87,7 @@ func (r *Repository) LookupTokenKeyVersion(ctx context.Context, keyWrapper wrapp // are ignored. func (r *Repository) DeleteTokenKeyVersion(ctx context.Context, privateId string, opt ...Option) (int, error) { if privateId == "" { - return db.NoRowsAffected, fmt.Errorf("delete token key version: missing private id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete token key version: missing private id: %w", errors.ErrInvalidParameter) } k := AllocTokenKeyVersion() k.PrivateId = privateId @@ -104,7 +105,7 @@ func (r *Repository) DeleteTokenKeyVersion(ctx context.Context, privateId string // no token entries for the key version rowsDeleted, err = w.Delete(ctx, dk) if err == nil && rowsDeleted > 1 { - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, @@ -117,20 +118,20 @@ func (r *Repository) DeleteTokenKeyVersion(ctx context.Context, privateId string // LatestTokenKeyVersion searches for the key version with the highest // version number. When no results are found, it returns nil, -// db.ErrRecordNotFound. +// errors.ErrRecordNotFound. func (r *Repository) LatestTokenKeyVersion(ctx context.Context, rkvWrapper wrapping.Wrapper, tokenKeyId string, opt ...Option) (*TokenKeyVersion, error) { if tokenKeyId == "" { - return nil, fmt.Errorf("latest token key version: missing token key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("latest token key version: missing token key id: %w", errors.ErrInvalidParameter) } if rkvWrapper == nil { - return nil, fmt.Errorf("latest token key version: missing root key version wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("latest token key version: missing root key version wrapper: %w", errors.ErrInvalidParameter) } var foundKeys []*TokenKeyVersion if err := r.reader.SearchWhere(ctx, &foundKeys, "token_key_id = ?", []interface{}{tokenKeyId}, db.WithLimit(1), db.WithOrder("version desc")); err != nil { return nil, fmt.Errorf("latest token key version: failed %w for %s", err, tokenKeyId) } if len(foundKeys) == 0 { - return nil, db.ErrRecordNotFound + return nil, errors.ErrRecordNotFound } if err := foundKeys[0].Decrypt(ctx, rkvWrapper); err != nil { return nil, fmt.Errorf("latest token key version: %w", err) @@ -141,10 +142,10 @@ func (r *Repository) LatestTokenKeyVersion(ctx context.Context, rkvWrapper wrapp // ListTokenKeyVersions will lists versions of a key. Supports the WithLimit option. func (r *Repository) ListTokenKeyVersions(ctx context.Context, rkvWrapper wrapping.Wrapper, tokenKeyId string, opt ...Option) ([]DekVersion, error) { if tokenKeyId == "" { - return nil, fmt.Errorf("list token key versions: missing token key id %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list token key versions: missing token key id %w", errors.ErrInvalidParameter) } if rkvWrapper == nil { - return nil, fmt.Errorf("list token key versions: missing root key version wrapper: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list token key versions: missing root key version wrapper: %w", errors.ErrInvalidParameter) } var versions []*TokenKeyVersion err := r.list(ctx, &versions, "token_key_id = ?", []interface{}{tokenKeyId}, opt...) diff --git a/internal/kms/repository_token_key_version_test.go b/internal/kms/repository_token_key_version_test.go index 333a2ef7d..693f88edf 100644 --- a/internal/kms/repository_token_key_version_test.go +++ b/internal/kms/repository_token_key_version_test.go @@ -2,11 +2,11 @@ package kms_test import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -67,7 +67,7 @@ func TestRepository_CreateTokenKeyVersion(t *testing.T) { tokenKeyId: dk.PrivateId, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "nil-wrapper", @@ -76,7 +76,7 @@ func TestRepository_CreateTokenKeyVersion(t *testing.T) { keyWrapper: nil, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -100,7 +100,7 @@ func TestRepository_CreateTokenKeyVersion(t *testing.T) { // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, k.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } @@ -147,7 +147,7 @@ func TestRepository_DeleteTokenKeyVersion(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "not-found", @@ -163,7 +163,7 @@ func TestRepository_DeleteTokenKeyVersion(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsError: db.ErrRecordNotFound, + wantIsError: errors.ErrRecordNotFound, }, } for _, tt := range tests { @@ -178,7 +178,7 @@ func TestRepository_DeleteTokenKeyVersion(t *testing.T) { } err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) @@ -186,12 +186,12 @@ func TestRepository_DeleteTokenKeyVersion(t *testing.T) { foundKey, err := repo.LookupTokenKeyVersion(context.Background(), wrapper, tt.args.key.PrivateId) assert.Error(err) assert.Nil(foundKey) - assert.True(errors.Is(err, db.ErrRecordNotFound)) + assert.True(errors.Is(err, errors.ErrRecordNotFound)) // make sure there was no oplog written err = db.TestVerifyOplog(t, rw, tt.args.key.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } @@ -236,14 +236,14 @@ func TestRepository_LatestTokenKeyVersion(t *testing.T) { createCnt: 0, keyWrapper: rkvWrapper, wantErr: true, - wantIsError: db.ErrRecordNotFound, + wantIsError: errors.ErrRecordNotFound, }, { name: "nil-wrapper", createCnt: 5, keyWrapper: nil, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { diff --git a/internal/kms/root_key.go b/internal/kms/root_key.go index 96fac745f..b923f83ea 100644 --- a/internal/kms/root_key.go +++ b/internal/kms/root_key.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms/store" "google.golang.org/protobuf/proto" ) @@ -24,7 +25,7 @@ type RootKey struct { // are currently supported. func NewRootKey(scopeId string, opt ...Option) (*RootKey, error) { if scopeId == "" { - return nil, fmt.Errorf("new root key: missing scope id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new root key: missing scope id: %w", errors.ErrInvalidParameter) } c := &RootKey{ RootKey: &store.RootKey{ @@ -53,15 +54,15 @@ func (k *RootKey) Clone() interface{} { // before it's written. func (k *RootKey) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if k.PrivateId == "" { - return fmt.Errorf("root key vet for write: missing private id: %w", db.ErrInvalidParameter) + return fmt.Errorf("root key vet for write: missing private id: %w", errors.ErrInvalidParameter) } switch opType { case db.CreateOp: if k.ScopeId == "" { - return fmt.Errorf("root key vet for write: missing scope id: %w", db.ErrInvalidParameter) + return fmt.Errorf("root key vet for write: missing scope id: %w", errors.ErrInvalidParameter) } case db.UpdateOp: - return fmt.Errorf("root key vet for write: key is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("root key vet for write: key is immutable: %w", errors.ErrInvalidParameter) } return nil } diff --git a/internal/kms/root_key_test.go b/internal/kms/root_key_test.go index 77ba5f8f9..c1044ee33 100644 --- a/internal/kms/root_key_test.go +++ b/internal/kms/root_key_test.go @@ -2,10 +2,10 @@ package kms_test import ( "context" - "errors" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/stretchr/testify/assert" @@ -38,7 +38,7 @@ func TestRootKey_Create(t *testing.T) { name: "empty-scopeId", args: args{}, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid-org-config", @@ -148,7 +148,7 @@ func TestRootKey_Delete(t *testing.T) { foundKey.PrivateId = tt.key.PrivateId err = rw.LookupById(context.Background(), &foundKey) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/kms/root_key_version.go b/internal/kms/root_key_version.go index 77817ae45..a506b9e95 100644 --- a/internal/kms/root_key_version.go +++ b/internal/kms/root_key_version.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms/store" wrapping "github.com/hashicorp/go-kms-wrapping" "github.com/hashicorp/go-kms-wrapping/structwrapping" @@ -24,10 +25,10 @@ type RootKeyVersion struct { // currently supported. func NewRootKeyVersion(rootKeyId string, key []byte, opt ...Option) (*RootKeyVersion, error) { if rootKeyId == "" { - return nil, fmt.Errorf("new root key version: missing root key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new root key version: missing root key id: %w", errors.ErrInvalidParameter) } if len(key) == 0 { - return nil, fmt.Errorf("new root key version: missing key: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new root key version: missing key: %w", errors.ErrInvalidParameter) } k := &RootKeyVersion{ @@ -58,18 +59,18 @@ func (k *RootKeyVersion) Clone() interface{} { // version before it's written. func (k *RootKeyVersion) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if k.PrivateId == "" { - return fmt.Errorf("root key version vet for write: missing private id: %w", db.ErrInvalidParameter) + return fmt.Errorf("root key version vet for write: missing private id: %w", errors.ErrInvalidParameter) } switch opType { case db.CreateOp: if k.CtKey == nil { - return fmt.Errorf("root key version vet for write: missing key: %w", db.ErrInvalidParameter) + return fmt.Errorf("root key version vet for write: missing key: %w", errors.ErrInvalidParameter) } if k.RootKeyId == "" { - return fmt.Errorf("root key version vet for write: missing root key id: %w", db.ErrInvalidParameter) + return fmt.Errorf("root key version vet for write: missing root key id: %w", errors.ErrInvalidParameter) } case db.UpdateOp: - return fmt.Errorf("root key version vet for write: key is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("root key version vet for write: key is immutable: %w", errors.ErrInvalidParameter) } return nil } diff --git a/internal/kms/root_key_version_test.go b/internal/kms/root_key_version_test.go index a7887c9e7..224cc76ca 100644 --- a/internal/kms/root_key_version_test.go +++ b/internal/kms/root_key_version_test.go @@ -2,10 +2,10 @@ package kms_test import ( "context" - "errors" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/kms/store" @@ -44,7 +44,7 @@ func TestRootKeyVersion_Create(t *testing.T) { key: []byte("test key"), }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-key", @@ -52,7 +52,7 @@ func TestRootKeyVersion_Create(t *testing.T) { rootId: rootKey.PrivateId, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid", @@ -155,7 +155,7 @@ func TestRootKeyVersion_Delete(t *testing.T) { foundKey.PrivateId = tt.key.PrivateId err = rw.LookupById(context.Background(), &foundKey) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/kms/session_key.go b/internal/kms/session_key.go index 6ca6215a3..5cdcf5a08 100644 --- a/internal/kms/session_key.go +++ b/internal/kms/session_key.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms/store" "google.golang.org/protobuf/proto" ) @@ -22,7 +23,7 @@ type SessionKey struct { // are currently supported. func NewSessionKey(rootKeyId string, opt ...Option) (*SessionKey, error) { if rootKeyId == "" { - return nil, fmt.Errorf("new root key: missing root key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new root key: missing root key id: %w", errors.ErrInvalidParameter) } c := &SessionKey{ SessionKey: &store.SessionKey{ @@ -51,11 +52,11 @@ func (k *SessionKey) Clone() interface{} { // before it's written. func (k *SessionKey) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if k.PrivateId == "" { - return fmt.Errorf("session key vet for write: missing private id: %w", db.ErrInvalidParameter) + return fmt.Errorf("session key vet for write: missing private id: %w", errors.ErrInvalidParameter) } if opType == db.CreateOp { if k.RootKeyId == "" { - return fmt.Errorf("session key vet for write: missing root key id: %w", db.ErrInvalidParameter) + return fmt.Errorf("session key vet for write: missing root key id: %w", errors.ErrInvalidParameter) } } return nil diff --git a/internal/kms/session_key_test.go b/internal/kms/session_key_test.go index 2385010ca..3259994d5 100644 --- a/internal/kms/session_key_test.go +++ b/internal/kms/session_key_test.go @@ -2,10 +2,10 @@ package kms_test import ( "context" - "errors" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/stretchr/testify/assert" @@ -41,7 +41,7 @@ func TestSessionKey_Create(t *testing.T) { name: "empty-rootKeyId", args: args{}, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid", @@ -141,7 +141,7 @@ func TestSessionKey_Delete(t *testing.T) { foundKey.PrivateId = tt.key.PrivateId err = rw.LookupById(context.Background(), &foundKey) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/kms/session_key_version.go b/internal/kms/session_key_version.go index c26e2e688..b524dfc71 100644 --- a/internal/kms/session_key_version.go +++ b/internal/kms/session_key_version.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms/store" wrapping "github.com/hashicorp/go-kms-wrapping" "github.com/hashicorp/go-kms-wrapping/structwrapping" @@ -24,13 +25,13 @@ type SessionKeyVersion struct { // currently supported. func NewSessionKeyVersion(sessionKeyId string, key []byte, rootKeyVersionId string, opt ...Option) (*SessionKeyVersion, error) { if sessionKeyId == "" { - return nil, fmt.Errorf("new session key version: missing session key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new session key version: missing session key id: %w", errors.ErrInvalidParameter) } if len(key) == 0 { - return nil, fmt.Errorf("new session key version: missing key: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new session key version: missing key: %w", errors.ErrInvalidParameter) } if rootKeyVersionId == "" { - return nil, fmt.Errorf("new session key version: missing root key version id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new session key version: missing root key version id: %w", errors.ErrInvalidParameter) } k := &SessionKeyVersion{ @@ -62,17 +63,17 @@ func (k *SessionKeyVersion) Clone() interface{} { // version before it's written. func (k *SessionKeyVersion) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if k.PrivateId == "" { - return fmt.Errorf("session key version vet for write: missing private id: %w", db.ErrInvalidParameter) + return fmt.Errorf("session key version vet for write: missing private id: %w", errors.ErrInvalidParameter) } if opType == db.CreateOp { if k.CtKey == nil { - return fmt.Errorf("session key version vet for write: missing key: %w", db.ErrInvalidParameter) + return fmt.Errorf("session key version vet for write: missing key: %w", errors.ErrInvalidParameter) } if k.SessionKeyId == "" { - return fmt.Errorf("session key version vet for write: missing session key id: %w", db.ErrInvalidParameter) + return fmt.Errorf("session key version vet for write: missing session key id: %w", errors.ErrInvalidParameter) } if k.RootKeyVersionId == "" { - return fmt.Errorf("session key version vet for write: missing root key version id: %w", db.ErrInvalidParameter) + return fmt.Errorf("session key version vet for write: missing root key version id: %w", errors.ErrInvalidParameter) } } return nil diff --git a/internal/kms/session_key_version_test.go b/internal/kms/session_key_version_test.go index fc53dcbd4..25a392229 100644 --- a/internal/kms/session_key_version_test.go +++ b/internal/kms/session_key_version_test.go @@ -2,10 +2,10 @@ package kms_test import ( "context" - "errors" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/stretchr/testify/assert" @@ -49,7 +49,7 @@ func TestSessionKeyVersion_Create(t *testing.T) { rootKeyVersionId: rkv.PrivateId, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-key", @@ -58,7 +58,7 @@ func TestSessionKeyVersion_Create(t *testing.T) { rootKeyVersionId: rkv.PrivateId, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-root-key-version-id", @@ -67,7 +67,7 @@ func TestSessionKeyVersion_Create(t *testing.T) { key: []byte("test key"), }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid", @@ -175,7 +175,7 @@ func TestSessionKeyVersion_Delete(t *testing.T) { foundKey.PrivateId = tt.key.PrivateId err = rw.LookupById(context.Background(), &foundKey) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/kms/token_key.go b/internal/kms/token_key.go index dcea1aa16..de22c2c6d 100644 --- a/internal/kms/token_key.go +++ b/internal/kms/token_key.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms/store" "google.golang.org/protobuf/proto" ) @@ -22,7 +23,7 @@ type TokenKey struct { // are currently supported. func NewTokenKey(rootKeyId string, opt ...Option) (*TokenKey, error) { if rootKeyId == "" { - return nil, fmt.Errorf("new root key: missing root key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new root key: missing root key id: %w", errors.ErrInvalidParameter) } c := &TokenKey{ TokenKey: &store.TokenKey{ @@ -51,11 +52,11 @@ func (k *TokenKey) Clone() interface{} { // before it's written. func (k *TokenKey) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if k.PrivateId == "" { - return fmt.Errorf("token key vet for write: missing private id: %w", db.ErrInvalidParameter) + return fmt.Errorf("token key vet for write: missing private id: %w", errors.ErrInvalidParameter) } if opType == db.CreateOp { if k.RootKeyId == "" { - return fmt.Errorf("token key vet for write: missing root key id: %w", db.ErrInvalidParameter) + return fmt.Errorf("token key vet for write: missing root key id: %w", errors.ErrInvalidParameter) } } return nil diff --git a/internal/kms/token_key_test.go b/internal/kms/token_key_test.go index afdd901b1..153ae7344 100644 --- a/internal/kms/token_key_test.go +++ b/internal/kms/token_key_test.go @@ -2,10 +2,11 @@ package kms_test import ( "context" - "errors" + "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/stretchr/testify/assert" @@ -41,7 +42,7 @@ func TestTokenKey_Create(t *testing.T) { name: "empty-rootKeyId", args: args{}, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid", @@ -141,7 +142,7 @@ func TestTokenKey_Delete(t *testing.T) { foundKey.PrivateId = tt.key.PrivateId err = rw.LookupById(context.Background(), &foundKey) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/kms/token_key_version.go b/internal/kms/token_key_version.go index 748546636..6ab6ea313 100644 --- a/internal/kms/token_key_version.go +++ b/internal/kms/token_key_version.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms/store" wrapping "github.com/hashicorp/go-kms-wrapping" "github.com/hashicorp/go-kms-wrapping/structwrapping" @@ -24,13 +25,13 @@ type TokenKeyVersion struct { // currently supported. func NewTokenKeyVersion(tokenKeyId string, key []byte, rootKeyVersionId string, opt ...Option) (*TokenKeyVersion, error) { if tokenKeyId == "" { - return nil, fmt.Errorf("new token key version: missing token key id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new token key version: missing token key id: %w", errors.ErrInvalidParameter) } if len(key) == 0 { - return nil, fmt.Errorf("new token key version: missing key: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new token key version: missing key: %w", errors.ErrInvalidParameter) } if rootKeyVersionId == "" { - return nil, fmt.Errorf("new token key version: missing root key version id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new token key version: missing root key version id: %w", errors.ErrInvalidParameter) } k := &TokenKeyVersion{ @@ -62,17 +63,17 @@ func (k *TokenKeyVersion) Clone() interface{} { // version before it's written. func (k *TokenKeyVersion) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if k.PrivateId == "" { - return fmt.Errorf("token key version vet for write: missing private id: %w", db.ErrInvalidParameter) + return fmt.Errorf("token key version vet for write: missing private id: %w", errors.ErrInvalidParameter) } if opType == db.CreateOp { if k.CtKey == nil { - return fmt.Errorf("token key version vet for write: missing key: %w", db.ErrInvalidParameter) + return fmt.Errorf("token key version vet for write: missing key: %w", errors.ErrInvalidParameter) } if k.TokenKeyId == "" { - return fmt.Errorf("token key version vet for write: missing token key id: %w", db.ErrInvalidParameter) + return fmt.Errorf("token key version vet for write: missing token key id: %w", errors.ErrInvalidParameter) } if k.RootKeyVersionId == "" { - return fmt.Errorf("token key version vet for write: missing root key version id: %w", db.ErrInvalidParameter) + return fmt.Errorf("token key version vet for write: missing root key version id: %w", errors.ErrInvalidParameter) } } return nil diff --git a/internal/kms/token_key_version_test.go b/internal/kms/token_key_version_test.go index 33af96de6..a229b5169 100644 --- a/internal/kms/token_key_version_test.go +++ b/internal/kms/token_key_version_test.go @@ -2,10 +2,10 @@ package kms_test import ( "context" - "errors" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/stretchr/testify/assert" @@ -49,7 +49,7 @@ func TestTokenKeyVersion_Create(t *testing.T) { rootKeyVersionId: rkv.PrivateId, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-key", @@ -58,7 +58,7 @@ func TestTokenKeyVersion_Create(t *testing.T) { rootKeyVersionId: rkv.PrivateId, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-root-key-version-id", @@ -67,7 +67,7 @@ func TestTokenKeyVersion_Create(t *testing.T) { key: []byte("test key"), }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid", @@ -175,7 +175,7 @@ func TestTokenKeyVersion_Delete(t *testing.T) { foundKey.PrivateId = tt.key.PrivateId err = rw.LookupById(context.Background(), &foundKey) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/servers/controller/handlers/accounts/account_service.go b/internal/servers/controller/handlers/accounts/account_service.go index 1c8516218..e5103d8ba 100644 --- a/internal/servers/controller/handlers/accounts/account_service.go +++ b/internal/servers/controller/handlers/accounts/account_service.go @@ -2,13 +2,12 @@ package accounts import ( "context" - "errors" "fmt" "github.com/hashicorp/boundary/internal/auth" "github.com/hashicorp/boundary/internal/auth/password" "github.com/hashicorp/boundary/internal/auth/password/store" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/accounts" pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" "github.com/hashicorp/boundary/internal/servers/controller/common" @@ -172,7 +171,7 @@ func (s Service) getFromRepo(ctx context.Context, id string) (*pb.Account, error } u, err := repo.LookupAccount(ctx, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, handlers.NotFoundErrorf("Account %q doesn't exist.", id) } return nil, err @@ -272,7 +271,7 @@ func (s Service) deleteFromRepo(ctx context.Context, scopeId, id string) (bool, } rows, err := repo.DeleteAccount(ctx, scopeId, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return false, nil } return false, fmt.Errorf("unable to delete account: %w", err) @@ -308,7 +307,7 @@ func (s Service) changePasswordInRepo(ctx context.Context, scopeId, id string, v out, err := repo.ChangePassword(ctx, scopeId, id, currentPassword, newPassword, version) if err != nil { switch { - case errors.Is(err, db.ErrRecordNotFound): + case errors.Is(err, errors.ErrRecordNotFound): return nil, handlers.NotFoundErrorf("Account not found.") case errors.Is(err, password.ErrTooShort): return nil, handlers.InvalidArgumentErrorf("Error in provided request.", @@ -333,7 +332,7 @@ func (s Service) setPasswordInRepo(ctx context.Context, scopeId, id string, vers out, err := repo.SetPassword(ctx, scopeId, id, pw, version) if err != nil { switch { - case errors.Is(err, db.ErrRecordNotFound): + case errors.Is(err, errors.ErrRecordNotFound): return nil, handlers.NotFoundErrorf("Account not found.") case errors.Is(err, password.ErrTooShort): return nil, handlers.InvalidArgumentErrorf("Error in provided request.", diff --git a/internal/servers/controller/handlers/authmethods/authmethod_service.go b/internal/servers/controller/handlers/authmethods/authmethod_service.go index 54e63180b..4be35beba 100644 --- a/internal/servers/controller/handlers/authmethods/authmethod_service.go +++ b/internal/servers/controller/handlers/authmethods/authmethod_service.go @@ -2,7 +2,7 @@ package authmethods import ( "context" - "errors" + stderrors "errors" "fmt" "strings" @@ -10,7 +10,7 @@ import ( "github.com/hashicorp/boundary/internal/auth/password" "github.com/hashicorp/boundary/internal/auth/password/store" "github.com/hashicorp/boundary/internal/authtoken" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/authmethods" pba "github.com/hashicorp/boundary/internal/gen/controller/api/resources/authtokens" "github.com/hashicorp/boundary/internal/gen/controller/api/resources/scopes" @@ -53,7 +53,7 @@ type Service struct { // NewService returns a auth method service which handles auth method related requests to boundary. func NewService(kms *kms.Kms, pwRepoFn common.PasswordAuthRepoFactory, iamRepoFn common.IamRepoFactory, atRepoFn common.AuthTokenRepoFactory) (Service, error) { if kms == nil { - return Service{}, errors.New("nil kms provided") + return Service{}, stderrors.New("nil kms provided") } if pwRepoFn == nil { return Service{}, fmt.Errorf("nil password repository provided") @@ -176,7 +176,7 @@ func (s Service) getFromRepo(ctx context.Context, id string) (*pb.AuthMethod, er } u, err := repo.LookupAuthMethod(ctx, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, handlers.NotFoundErrorf("AuthMethod %q doesn't exist.", id) } return nil, err @@ -285,7 +285,7 @@ func (s Service) deleteFromRepo(ctx context.Context, scopeId, id string) (bool, } rows, err := repo.DeleteAuthMethod(ctx, scopeId, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return false, nil } return false, fmt.Errorf("unable to delete auth method: %w", err) diff --git a/internal/servers/controller/handlers/authtokens/authtoken_service.go b/internal/servers/controller/handlers/authtokens/authtoken_service.go index c4ac38963..59c9e82e9 100644 --- a/internal/servers/controller/handlers/authtokens/authtoken_service.go +++ b/internal/servers/controller/handlers/authtokens/authtoken_service.go @@ -2,12 +2,11 @@ package authtokens import ( "context" - "errors" "fmt" "github.com/hashicorp/boundary/internal/auth" "github.com/hashicorp/boundary/internal/authtoken" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/authtokens" pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" "github.com/hashicorp/boundary/internal/servers/controller/common" @@ -95,7 +94,7 @@ func (s Service) getFromRepo(ctx context.Context, id string) (*pb.AuthToken, err } u, err := repo.LookupAuthToken(ctx, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, handlers.NotFoundErrorf("AuthToken %q doesn't exist.", id) } return nil, fmt.Errorf("unable to lookup auth token: %w", err) @@ -113,7 +112,7 @@ func (s Service) deleteFromRepo(ctx context.Context, id string) (bool, error) { } rows, err := repo.DeleteAuthToken(ctx, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return false, nil } return false, fmt.Errorf("unable to delete user: %w", err) diff --git a/internal/servers/controller/handlers/errors.go b/internal/servers/controller/handlers/errors.go index d6712a872..ab2d43f0d 100644 --- a/internal/servers/controller/handlers/errors.go +++ b/internal/servers/controller/handlers/errors.go @@ -2,7 +2,6 @@ package handlers import ( "context" - "errors" "fmt" "io" "net/http" @@ -10,7 +9,7 @@ import ( "strings" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" pb "github.com/hashicorp/boundary/internal/gen/controller/api" "github.com/hashicorp/go-hclog" "github.com/hashicorp/vault/sdk/helper/base62" @@ -138,11 +137,11 @@ func backendErrorToApiError(inErr error) error { Code: codes.Unimplemented.String(), Message: stErr.Message(), }} - case errors.Is(inErr, db.ErrRecordNotFound): + case errors.Is(inErr, errors.ErrRecordNotFound): return NotFoundErrorf(genericNotFoundMsg) - case errors.Is(inErr, db.ErrInvalidFieldMask), errors.Is(inErr, db.ErrEmptyFieldMask): + case errors.Is(inErr, errors.ErrInvalidFieldMask), errors.Is(inErr, errors.ErrEmptyFieldMask): return InvalidArgumentErrorf("Error in provided request", map[string]string{"update_mask": "Invalid update mask provided."}) - case db.IsUniqueError(inErr), errors.Is(inErr, db.ErrNotUnique): + case errors.IsUniqueError(inErr), errors.Is(inErr, errors.ErrNotUnique): return InvalidArgumentErrorf(genericUniquenessMsg, nil) } return nil diff --git a/internal/servers/controller/handlers/errors_test.go b/internal/servers/controller/handlers/errors_test.go index a643728c8..609867597 100644 --- a/internal/servers/controller/handlers/errors_test.go +++ b/internal/servers/controller/handlers/errors_test.go @@ -2,7 +2,7 @@ package handlers import ( "context" - "errors" + stderrors "errors" "fmt" "io/ioutil" "net/http" @@ -11,7 +11,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" pb "github.com/hashicorp/boundary/internal/gen/controller/api" "github.com/hashicorp/go-hclog" "github.com/stretchr/testify/assert" @@ -88,7 +88,7 @@ func TestApiErrorHandler(t *testing.T) { }, { name: "Unknown error", - err: errors.New("Some random error"), + err: stderrors.New("Some random error"), expected: &pb.Error{ Status: http.StatusInternalServerError, Code: "Internal", @@ -97,7 +97,7 @@ func TestApiErrorHandler(t *testing.T) { }, { name: "Db invalid public id error", - err: fmt.Errorf("test error: %w", db.ErrInvalidPublicId), + err: fmt.Errorf("test error: %w", errors.ErrInvalidPublicId), expected: &pb.Error{ Status: http.StatusInternalServerError, Code: "Internal", @@ -106,7 +106,7 @@ func TestApiErrorHandler(t *testing.T) { }, { name: "Db invalid parameter", - err: fmt.Errorf("test error: %w", db.ErrInvalidParameter), + err: fmt.Errorf("test error: %w", errors.ErrInvalidParameter), expected: &pb.Error{ Status: http.StatusInternalServerError, Code: "Internal", @@ -115,7 +115,7 @@ func TestApiErrorHandler(t *testing.T) { }, { name: "Db invalid field mask", - err: fmt.Errorf("test error: %w", db.ErrInvalidFieldMask), + err: fmt.Errorf("test error: %w", errors.ErrInvalidFieldMask), expected: &pb.Error{ Status: http.StatusBadRequest, Code: "InvalidArgument", @@ -125,7 +125,7 @@ func TestApiErrorHandler(t *testing.T) { }, { name: "Db empty field mask", - err: fmt.Errorf("test error: %w", db.ErrEmptyFieldMask), + err: fmt.Errorf("test error: %w", errors.ErrEmptyFieldMask), expected: &pb.Error{ Status: http.StatusBadRequest, Code: "InvalidArgument", @@ -135,7 +135,7 @@ func TestApiErrorHandler(t *testing.T) { }, { name: "Db not unique", - err: fmt.Errorf("test error: %w", db.ErrNotUnique), + err: fmt.Errorf("test error: %w", errors.ErrNotUnique), expected: &pb.Error{ Status: http.StatusBadRequest, Code: "InvalidArgument", @@ -144,7 +144,7 @@ func TestApiErrorHandler(t *testing.T) { }, { name: "Db record not found", - err: fmt.Errorf("test error: %w", db.ErrRecordNotFound), + err: fmt.Errorf("test error: %w", errors.ErrRecordNotFound), expected: &pb.Error{ Status: http.StatusNotFound, Code: "NotFound", @@ -153,7 +153,7 @@ func TestApiErrorHandler(t *testing.T) { }, { name: "Db multiple records", - err: fmt.Errorf("test error: %w", db.ErrMultipleRecords), + err: fmt.Errorf("test error: %w", errors.ErrMultipleRecords), expected: &pb.Error{ Status: http.StatusInternalServerError, Code: "Internal", diff --git a/internal/servers/controller/handlers/groups/group_service.go b/internal/servers/controller/handlers/groups/group_service.go index 7ecd3be2c..45dae9598 100644 --- a/internal/servers/controller/handlers/groups/group_service.go +++ b/internal/servers/controller/handlers/groups/group_service.go @@ -2,11 +2,10 @@ package groups import ( "context" - "errors" "fmt" "github.com/hashicorp/boundary/internal/auth" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/groups" pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" "github.com/hashicorp/boundary/internal/iam" @@ -191,7 +190,7 @@ func (s Service) getFromRepo(ctx context.Context, id string) (*pb.Group, error) } g, m, err := repo.LookupGroup(ctx, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, handlers.NotFoundErrorf("Group %q doesn't exist.", id) } return nil, fmt.Errorf("unable to get group: %w", err) @@ -267,7 +266,7 @@ func (s Service) deleteFromRepo(ctx context.Context, id string) (bool, error) { } rows, err := repo.DeleteGroup(ctx, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return false, nil } return false, fmt.Errorf("unable to delete group: %w", err) diff --git a/internal/servers/controller/handlers/host_sets/host_set_service.go b/internal/servers/controller/handlers/host_sets/host_set_service.go index c62457695..cc0993f7c 100644 --- a/internal/servers/controller/handlers/host_sets/host_set_service.go +++ b/internal/servers/controller/handlers/host_sets/host_set_service.go @@ -2,11 +2,10 @@ package host_sets import ( "context" - "errors" "fmt" "github.com/hashicorp/boundary/internal/auth" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/hostsets" pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" "github.com/hashicorp/boundary/internal/host" @@ -219,7 +218,7 @@ func (s Service) createInRepo(ctx context.Context, scopeId, catalogId string, it } out, err := repo.CreateSet(ctx, scopeId, h) if err != nil { - if db.IsUniqueError(err) || errors.Is(err, db.ErrNotUnique) { + if errors.IsUniqueError(err) || errors.Is(err, errors.ErrNotUnique) { // Push this error through so the error interceptor can interpret it correctly. return nil, err } diff --git a/internal/servers/controller/handlers/hosts/host_service.go b/internal/servers/controller/handlers/hosts/host_service.go index c4f115fdb..b7c67b91e 100644 --- a/internal/servers/controller/handlers/hosts/host_service.go +++ b/internal/servers/controller/handlers/hosts/host_service.go @@ -2,13 +2,12 @@ package hosts import ( "context" - "errors" "fmt" "net" "strings" "github.com/hashicorp/boundary/internal/auth" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/hosts" pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" "github.com/hashicorp/boundary/internal/host" @@ -177,7 +176,7 @@ func (s Service) createInRepo(ctx context.Context, scopeId, catalogId string, it } out, err := repo.CreateHost(ctx, scopeId, h) if err != nil { - if db.IsUniqueError(err) || errors.Is(err, db.ErrNotUnique) { + if errors.IsUniqueError(err) || errors.Is(err, errors.ErrNotUnique) { // Push this error through so the error interceptor can interpret it correctly. return nil, err } diff --git a/internal/servers/controller/handlers/roles/role_service.go b/internal/servers/controller/handlers/roles/role_service.go index f5f99343f..0c0656802 100644 --- a/internal/servers/controller/handlers/roles/role_service.go +++ b/internal/servers/controller/handlers/roles/role_service.go @@ -2,11 +2,10 @@ package roles import ( "context" - "errors" "fmt" "github.com/hashicorp/boundary/internal/auth" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/roles" pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" "github.com/hashicorp/boundary/internal/iam" @@ -243,7 +242,7 @@ func (s Service) getFromRepo(ctx context.Context, id string) (*pb.Role, error) { } out, pr, roleGrants, err := repo.LookupRole(ctx, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, handlers.NotFoundErrorf("Role %q doesn't exist.", id) } return nil, err @@ -326,7 +325,7 @@ func (s Service) deleteFromRepo(ctx context.Context, id string) (bool, error) { } rows, err := repo.DeleteRole(ctx, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return false, nil } return false, fmt.Errorf("unable to delete role: %w", err) diff --git a/internal/servers/controller/handlers/sessions/session_service.go b/internal/servers/controller/handlers/sessions/session_service.go index 99026e8cb..efd5b2a7b 100644 --- a/internal/servers/controller/handlers/sessions/session_service.go +++ b/internal/servers/controller/handlers/sessions/session_service.go @@ -2,11 +2,11 @@ package sessions import ( "context" - "errors" + stderrors "errors" "fmt" "github.com/hashicorp/boundary/internal/auth" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/sessions" pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" "github.com/hashicorp/boundary/internal/servers/controller/common" @@ -97,7 +97,7 @@ func (s Service) getFromRepo(ctx context.Context, id string) (*pb.Session, error } sess, _, err := repo.LookupSession(ctx, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, handlers.NotFoundErrorf("Session %q doesn't exist.", id) } return nil, err @@ -176,7 +176,7 @@ func (s Service) authResult(ctx context.Context, id string, a action.Type) auth. parentId = t.ScopeId opts = append(opts, auth.WithId(id)) default: - res.Error = errors.New("unsupported action") + res.Error = stderrors.New("unsupported action") return res } opts = append(opts, auth.WithScopeId(parentId)) @@ -197,10 +197,10 @@ func toProto(in *session.Session) *pb.Session { Type: target.SubtypeFromId(in.TargetId).String(), // TODO: Provide the ServerType and the ServerId when that information becomes relevant in the API. - CreatedTime: in.CreateTime.GetTimestamp(), - UpdatedTime: in.UpdateTime.GetTimestamp(), - ExpirationTime: in.ExpirationTime.GetTimestamp(), - Certificate: in.Certificate, + CreatedTime: in.CreateTime.GetTimestamp(), + UpdatedTime: in.UpdateTime.GetTimestamp(), + ExpirationTime: in.ExpirationTime.GetTimestamp(), + Certificate: in.Certificate, TerminationReason: in.TerminationReason, } if len(in.States) > 0 { diff --git a/internal/servers/controller/handlers/targets/target_service.go b/internal/servers/controller/handlers/targets/target_service.go index 9fc5a0354..b9c4f7df4 100644 --- a/internal/servers/controller/handlers/targets/target_service.go +++ b/internal/servers/controller/handlers/targets/target_service.go @@ -2,7 +2,7 @@ package targets import ( "context" - "errors" + stderrors "errors" "fmt" "math/rand" "net/url" @@ -10,8 +10,8 @@ import ( "github.com/golang/protobuf/ptypes/wrappers" "github.com/hashicorp/boundary/internal/auth" - "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/db/timestamp" + "github.com/hashicorp/boundary/internal/errors" pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/targets" pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" "github.com/hashicorp/boundary/internal/host" @@ -241,14 +241,14 @@ func (s Service) AuthorizeSession(ctx context.Context, req *pbs.AuthorizeSession } if authResults.RoundTripValue == nil { - return nil, errors.New("authorize session: expected to get a target back from auth results") + return nil, stderrors.New("authorize session: expected to get a target back from auth results") } t, ok := authResults.RoundTripValue.(target.Target) if !ok { - return nil, errors.New("authorize session: round tripped auth results value is not a target") + return nil, stderrors.New("authorize session: round tripped auth results value is not a target") } if t == nil { - return nil, errors.New("authorize session: round tripped target is nil") + return nil, stderrors.New("authorize session: round tripped target is nil") } // This could happen if, say, u_recovery was used or u_anon was granted. But @@ -276,7 +276,7 @@ func (s Service) AuthorizeSession(ctx context.Context, req *pbs.AuthorizeSession } t, hostSets, err := repo.LookupTarget(ctx, t.GetPublicId()) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, handlers.NotFoundErrorf("Target %q not found.", t.GetPublicId()) } return nil, err @@ -360,7 +360,7 @@ HostSetIterationLoop: } endpointHost = h.Address if endpointHost == "" { - return nil, errors.New("host had empty address") + return nil, stderrors.New("host had empty address") } } if defaultPort != 0 { @@ -444,7 +444,7 @@ func (s Service) getFromRepo(ctx context.Context, id string) (*pb.Target, error) } u, m, err := repo.LookupTarget(ctx, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, handlers.NotFoundErrorf("Target %q doesn't exist.", id) } return nil, err @@ -543,7 +543,7 @@ func (s Service) deleteFromRepo(ctx context.Context, id string) (bool, error) { } rows, err := repo.DeleteTarget(ctx, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return false, nil } return false, fmt.Errorf("unable to delete target: %w", err) diff --git a/internal/servers/controller/handlers/users/user_service.go b/internal/servers/controller/handlers/users/user_service.go index 4b22cbeaa..2bf3dbf05 100644 --- a/internal/servers/controller/handlers/users/user_service.go +++ b/internal/servers/controller/handlers/users/user_service.go @@ -2,12 +2,11 @@ package users import ( "context" - "errors" "fmt" "github.com/hashicorp/boundary/internal/auth" "github.com/hashicorp/boundary/internal/auth/password" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/users" pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services" "github.com/hashicorp/boundary/internal/iam" @@ -192,7 +191,7 @@ func (s Service) getFromRepo(ctx context.Context, id string) (*pb.User, error) { } u, accts, err := repo.LookupUser(ctx, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, handlers.NotFoundErrorf("User %q doesn't exist.", id) } return nil, err @@ -268,7 +267,7 @@ func (s Service) deleteFromRepo(ctx context.Context, id string) (bool, error) { } rows, err := repo.DeleteUser(ctx, id) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return false, nil } return false, fmt.Errorf("unable to delete user: %w", err) diff --git a/internal/session/connection.go b/internal/session/connection.go index effe65220..e66c46126 100644 --- a/internal/session/connection.go +++ b/internal/session/connection.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/db/timestamp" + "github.com/hashicorp/boundary/internal/errors" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -109,7 +110,7 @@ func (c *Connection) Clone() interface{} { func (c *Connection) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { opts := db.GetOpts(opt...) if c.PublicId == "" { - return fmt.Errorf("connection vet for write: missing public id: %w", db.ErrInvalidParameter) + return fmt.Errorf("connection vet for write: missing public id: %w", errors.ErrInvalidParameter) } switch opType { case db.CreateOp: @@ -119,16 +120,16 @@ func (c *Connection) VetForWrite(ctx context.Context, r db.Reader, opType db.OpT case db.UpdateOp: switch { case contains(opts.WithFieldMaskPaths, "PublicId"): - return fmt.Errorf("connection vet for write: public id is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("connection vet for write: public id is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "SessionId"): - return fmt.Errorf("connection vet for write: session id is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("connection vet for write: session id is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "CreateTime"): - return fmt.Errorf("connection vet for write: create time is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("connection vet for write: create time is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "UpdateTime"): - return fmt.Errorf("connection vet for write: update time is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("connection vet for write: update time is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "ClosedReason"): if _, err := convertToClosedReason(c.ClosedReason); err != nil { - return fmt.Errorf("connection vet for write: %w", db.ErrInvalidParameter) + return fmt.Errorf("connection vet for write: %w", errors.ErrInvalidParameter) } } } @@ -153,19 +154,19 @@ func (c *Connection) SetTableName(n string) { // validateNewConnection checks everything but the connection's PublicId func (c *Connection) validateNewConnection(errorPrefix string) error { if c.SessionId == "" { - return fmt.Errorf("%s missing session id: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing session id: %w", errorPrefix, errors.ErrInvalidParameter) } if c.ClientTcpAddress == "" { - return fmt.Errorf("%s missing client address: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing client address: %w", errorPrefix, errors.ErrInvalidParameter) } if c.ClientTcpPort == 0 { - return fmt.Errorf("%s missing client port: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing client port: %w", errorPrefix, errors.ErrInvalidParameter) } if c.EndpointTcpAddress == "" { - return fmt.Errorf("%s missing endpoint address: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing endpoint address: %w", errorPrefix, errors.ErrInvalidParameter) } if c.EndpointTcpPort == 0 { - return fmt.Errorf("%s missing endpoint port: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing endpoint port: %w", errorPrefix, errors.ErrInvalidParameter) } return nil } diff --git a/internal/session/connection_closed_reason.go b/internal/session/connection_closed_reason.go index afe65f416..dcc5fd90c 100644 --- a/internal/session/connection_closed_reason.go +++ b/internal/session/connection_closed_reason.go @@ -3,7 +3,7 @@ package session import ( "fmt" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" ) // ClosedReason of the connection @@ -37,6 +37,6 @@ func convertToClosedReason(s string) (ClosedReason, error) { case ConnectionSystemError.String(): return ConnectionSystemError, nil default: - return "", fmt.Errorf("closed reason: %s is not a valid reason: %w", s, db.ErrInvalidParameter) + return "", fmt.Errorf("closed reason: %s is not a valid reason: %w", s, errors.ErrInvalidParameter) } } diff --git a/internal/session/connection_closed_with.go b/internal/session/connection_closed_with.go index f17b8f39a..b187072e5 100644 --- a/internal/session/connection_closed_with.go +++ b/internal/session/connection_closed_with.go @@ -3,7 +3,7 @@ package session import ( "fmt" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" ) // CloseWith defines the boundary data that is saved in the repo when the @@ -17,10 +17,10 @@ type CloseWith struct { func (c CloseWith) validate() error { if c.ConnectionId == "" { - return fmt.Errorf("missing connection id: %w", db.ErrInvalidParameter) + return fmt.Errorf("missing connection id: %w", errors.ErrInvalidParameter) } if c.ClosedReason.String() == "" { - return fmt.Errorf("missing closed reason: %w", db.ErrInvalidParameter) + return fmt.Errorf("missing closed reason: %w", errors.ErrInvalidParameter) } // 0 is valid for BytesUp and BytesDown return nil diff --git a/internal/session/connection_state.go b/internal/session/connection_state.go index 2a0f38f24..4ecd162e4 100644 --- a/internal/session/connection_state.go +++ b/internal/session/connection_state.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/db/timestamp" + "github.com/hashicorp/boundary/internal/errors" "google.golang.org/protobuf/types/known/timestamppb" workerpbs "github.com/hashicorp/boundary/internal/gen/controller/servers/services" @@ -140,19 +141,19 @@ func (s *ConnectionState) SetTableName(n string) { // validate checks the session state func (s *ConnectionState) validate(errorPrefix string) error { if s.Status == "" { - return fmt.Errorf("%s missing status: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing status: %w", errorPrefix, errors.ErrInvalidParameter) } if s.ConnectionId == "" { - return fmt.Errorf("%s missing connection id: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing connection id: %w", errorPrefix, errors.ErrInvalidParameter) } if s.StartTime != nil { - return fmt.Errorf("%s start time is not settable: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s start time is not settable: %w", errorPrefix, errors.ErrInvalidParameter) } if s.EndTime != nil { - return fmt.Errorf("%s end time is not settable: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s end time is not settable: %w", errorPrefix, errors.ErrInvalidParameter) } if s.PreviousEndTime != nil { - return fmt.Errorf("%s previous end time is not settable: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s previous end time is not settable: %w", errorPrefix, errors.ErrInvalidParameter) } return nil } diff --git a/internal/session/connection_state_test.go b/internal/session/connection_state_test.go index f08f635f4..88b605727 100644 --- a/internal/session/connection_state_test.go +++ b/internal/session/connection_state_test.go @@ -2,10 +2,10 @@ package session import ( "context" - "errors" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -50,7 +50,7 @@ func TestConnectionState_Create(t *testing.T) { status: StatusClosed, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-status", @@ -58,7 +58,7 @@ func TestConnectionState_Create(t *testing.T) { connectionId: connection.PublicId, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -150,7 +150,7 @@ func TestConnectionState_Delete(t *testing.T) { foundState := allocConnectionState() err = rw.LookupWhere(context.Background(), &foundState, "connection_id = ? and start_time = ?", tt.state.ConnectionId, initialState.StartTime) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/session/connection_test.go b/internal/session/connection_test.go index 49f51e68d..3d4f7af4c 100644 --- a/internal/session/connection_test.go +++ b/internal/session/connection_test.go @@ -2,10 +2,10 @@ package session import ( "context" - "errors" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -61,7 +61,7 @@ func TestConnection_Create(t *testing.T) { endpointTcpPort: 2222, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-client-address", @@ -72,7 +72,7 @@ func TestConnection_Create(t *testing.T) { endpointTcpPort: 2222, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-client-port", @@ -83,7 +83,7 @@ func TestConnection_Create(t *testing.T) { endpointTcpPort: 2222, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-endpoint-address", @@ -94,7 +94,7 @@ func TestConnection_Create(t *testing.T) { endpointTcpPort: 2222, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-endpoint-port", @@ -105,7 +105,7 @@ func TestConnection_Create(t *testing.T) { endpointTcpAddress: "127.0.0.1", }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -195,7 +195,7 @@ func TestConnection_Delete(t *testing.T) { foundConnection.PublicId = tt.connection.PublicId err = rw.LookupById(context.Background(), &foundConnection) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/session/repository_connection.go b/internal/session/repository_connection.go index 9ae829af7..99b5d2ba0 100644 --- a/internal/session/repository_connection.go +++ b/internal/session/repository_connection.go @@ -2,10 +2,11 @@ package session import ( "context" - "errors" + stderrors "errors" "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" ) // LookupConnection will look up a connection in the repository and return the connection @@ -13,7 +14,7 @@ import ( // No options are currently supported. func (r *Repository) LookupConnection(ctx context.Context, connectionId string, opt ...Option) (*Connection, []*ConnectionState, error) { if connectionId == "" { - return nil, nil, fmt.Errorf("lookup connection: missing connectionId id: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("lookup connection: missing connectionId id: %w", errors.ErrInvalidParameter) } connection := AllocConnection() connection.PublicId = connectionId @@ -34,7 +35,7 @@ func (r *Repository) LookupConnection(ctx context.Context, connectionId string, }, ) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, nil, nil } return nil, nil, fmt.Errorf("lookup connection: %w", err) @@ -56,7 +57,7 @@ func (r *Repository) ListConnections(ctx context.Context, sessionId string, opt // DeleteConnection will delete a connection from the repository. func (r *Repository) DeleteConnection(ctx context.Context, publicId string, opt ...Option) (int, error) { if publicId == "" { - return db.NoRowsAffected, fmt.Errorf("delete connection: missing public id %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete connection: missing public id %w", errors.ErrInvalidParameter) } connection := AllocConnection() connection.PublicId = publicId @@ -78,7 +79,7 @@ func (r *Repository) DeleteConnection(ctx context.Context, publicId string, opt ) if err == nil && rowsDeleted > 1 { // return err, which will result in a rollback of the delete - return errors.New("error more than 1 connection would have been deleted") + return stderrors.New("error more than 1 connection would have been deleted") } return err }, diff --git a/internal/session/repository_connection_test.go b/internal/session/repository_connection_test.go index 581ed5b24..c61f170ec 100644 --- a/internal/session/repository_connection_test.go +++ b/internal/session/repository_connection_test.go @@ -2,12 +2,12 @@ package session import ( "context" - "errors" "testing" "time" "github.com/golang/protobuf/ptypes" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" @@ -184,7 +184,7 @@ func TestRepository_DeleteConnection(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantErrMsg: "delete connection: failed record not found for ", + wantErrMsg: "delete connection: failed record not found:", }, } for _, tt := range tests { @@ -197,7 +197,7 @@ func TestRepository_DeleteConnection(t *testing.T) { assert.Contains(err.Error(), tt.wantErrMsg) err = db.TestVerifyOplog(t, rw, tt.args.connection.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } assert.NoError(err) diff --git a/internal/session/repository_session.go b/internal/session/repository_session.go index 49af3b761..98dec27bf 100644 --- a/internal/session/repository_session.go +++ b/internal/session/repository_session.go @@ -4,12 +4,13 @@ import ( "context" "crypto/ed25519" "crypto/subtle" - "errors" + stderrors "errors" "fmt" "strings" "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/db/timestamp" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" wrapping "github.com/hashicorp/go-kms-wrapping" "google.golang.org/grpc/codes" @@ -22,46 +23,46 @@ import ( // currently supported. func (r *Repository) CreateSession(ctx context.Context, sessionWrapper wrapping.Wrapper, newSession *Session, opt ...Option) (*Session, ed25519.PrivateKey, error) { if newSession == nil { - return nil, nil, fmt.Errorf("create session: missing session: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session: missing session: %w", errors.ErrInvalidParameter) } if newSession.PublicId != "" { - return nil, nil, fmt.Errorf("create session: public id is not empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session: public id is not empty: %w", errors.ErrInvalidParameter) } if len(newSession.Certificate) != 0 { - return nil, nil, fmt.Errorf("create session: certificate is not empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session: certificate is not empty: %w", errors.ErrInvalidParameter) } if newSession.TargetId == "" { - return nil, nil, fmt.Errorf("create session: target id is empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session: target id is empty: %w", errors.ErrInvalidParameter) } if newSession.HostId == "" { - return nil, nil, fmt.Errorf("create session: user id is empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session: user id is empty: %w", errors.ErrInvalidParameter) } if newSession.UserId == "" { - return nil, nil, fmt.Errorf("create session: user id is empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session: user id is empty: %w", errors.ErrInvalidParameter) } if newSession.HostSetId == "" { - return nil, nil, fmt.Errorf("create session: host set id is empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session: host set id is empty: %w", errors.ErrInvalidParameter) } if newSession.AuthTokenId == "" { - return nil, nil, fmt.Errorf("create session: auth token id is empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session: auth token id is empty: %w", errors.ErrInvalidParameter) } if newSession.ScopeId == "" { - return nil, nil, fmt.Errorf("create session: scope id is empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session: scope id is empty: %w", errors.ErrInvalidParameter) } if newSession.ServerId != "" { - return nil, nil, fmt.Errorf("create session: server id must be empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session: server id must be empty: %w", errors.ErrInvalidParameter) } if newSession.ServerType != "" { - return nil, nil, fmt.Errorf("create session: server type must be empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session: server type must be empty: %w", errors.ErrInvalidParameter) } if newSession.CtTofuToken != nil { - return nil, nil, fmt.Errorf("create session: ct must be empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session: ct must be empty: %w", errors.ErrInvalidParameter) } if newSession.TofuToken != nil { - return nil, nil, fmt.Errorf("create session: tofu token must be empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session: tofu token must be empty: %w", errors.ErrInvalidParameter) } if newSession.ExpirationTime == nil || newSession.ExpirationTime.Timestamp.AsTime().IsZero() { - return nil, nil, fmt.Errorf("create session: expiration is empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create session: expiration is empty: %w", errors.ErrInvalidParameter) } id, err := newId() @@ -116,7 +117,7 @@ func (r *Repository) CreateSession(ctx context.Context, sessionWrapper wrapping. // supported. func (r *Repository) LookupSession(ctx context.Context, sessionId string, opt ...Option) (*Session, *ConnectionAuthzSummary, error) { if sessionId == "" { - return nil, nil, fmt.Errorf("lookup session: missing sessionId id: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("lookup session: missing sessionId id: %w", errors.ErrInvalidParameter) } session := AllocSession() session.PublicId = sessionId @@ -137,7 +138,7 @@ func (r *Repository) LookupSession(ctx context.Context, sessionId string, opt .. }, ) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, nil, nil } return nil, nil, fmt.Errorf("lookup session: %w", err) @@ -231,7 +232,7 @@ func (r *Repository) ListSessions(ctx context.Context, opt ...Option) ([]*Sessio // DeleteSession will delete a session from the repository. func (r *Repository) DeleteSession(ctx context.Context, publicId string, opt ...Option) (int, error) { if publicId == "" { - return db.NoRowsAffected, fmt.Errorf("delete session: missing public id %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete session: missing public id %w", errors.ErrInvalidParameter) } session := AllocSession() session.PublicId = publicId @@ -253,7 +254,7 @@ func (r *Repository) DeleteSession(ctx context.Context, publicId string, opt ... ) if err == nil && rowsDeleted > 1 { // return err, which will result in a rollback of the delete - return errors.New("error more than 1 session would have been deleted") + return stderrors.New("error more than 1 session would have been deleted") } return err }, @@ -271,10 +272,10 @@ func (r *Repository) DeleteSession(ctx context.Context, publicId string, opt ... // idempotent. func (r *Repository) CancelSession(ctx context.Context, sessionId string, sessionVersion uint32) (*Session, error) { if sessionId == "" { - return nil, fmt.Errorf("cancel session: missing session id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("cancel session: missing session id: %w", errors.ErrInvalidParameter) } if sessionVersion == 0 { - return nil, fmt.Errorf("cancel session: missing session version: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("cancel session: missing session version: %w", errors.ErrInvalidParameter) } s, ss, err := r.updateState(ctx, sessionId, sessionVersion, StatusCanceling) if err != nil { @@ -289,10 +290,10 @@ func (r *Repository) CancelSession(ctx context.Context, sessionId string, sessio // are not closed. func (r *Repository) TerminateSession(ctx context.Context, sessionId string, sessionVersion uint32, reason TerminationReason) (*Session, error) { if sessionId == "" { - return nil, fmt.Errorf("terminate session: missing session id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("terminate session: missing session id: %w", errors.ErrInvalidParameter) } if sessionVersion == 0 { - return nil, fmt.Errorf("terminate session: version cannot be zero: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("terminate session: version cannot be zero: %w", errors.ErrInvalidParameter) } updatedSession := AllocSession() @@ -367,7 +368,7 @@ func (r *Repository) TerminateCompletedSessions(ctx context.Context) (int, error // an error of ErrInvalidStateForOperation. func (r *Repository) AuthorizeConnection(ctx context.Context, sessionId string) (*Connection, []*ConnectionState, *ConnectionAuthzSummary, error) { if sessionId == "" { - return nil, nil, nil, status.Errorf(codes.FailedPrecondition, "authorize connection: missing session id: %v", db.ErrInvalidParameter) + return nil, nil, nil, status.Errorf(codes.FailedPrecondition, "authorize connection: missing session id: %v", errors.ErrInvalidParameter) } connectionId, err := newConnectionId() if err != nil { @@ -466,7 +467,7 @@ func (r *Repository) ConnectConnection(ctx context.Context, c ConnectWith) (*Con } if err == nil && rowsUpdated > 1 { // return err, which will result in a rollback of the update - return errors.New("error more than 1 connection would have been updated ") + return stderrors.New("error more than 1 connection would have been updated ") } newState, err := NewConnectionState(connection.PublicId, StatusConnected) if err != nil { @@ -500,7 +501,7 @@ type CloseConnectionResp struct { // endpoint func (r *Repository) CloseConnections(ctx context.Context, closeWith []CloseWith, opt ...Option) ([]CloseConnectionResp, error) { if len(closeWith) == 0 { - return nil, fmt.Errorf("close connections: missing connections to close: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("close connections: missing connections to close: %w", errors.ErrInvalidParameter) } for _, cw := range closeWith { if err := cw.validate(); err != nil { @@ -559,19 +560,19 @@ func (r *Repository) CloseConnections(ctx context.Context, closeWith []CloseWith // was canceled or terminated. func (r *Repository) ActivateSession(ctx context.Context, sessionId string, sessionVersion uint32, serverId, serverType string, tofuToken []byte) (*Session, []*State, error) { if sessionId == "" { - return nil, nil, fmt.Errorf("activate session: missing session id: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("activate session: missing session id: %w", errors.ErrInvalidParameter) } if sessionVersion == 0 { - return nil, nil, fmt.Errorf("activate session: version cannot be zero: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("activate session: version cannot be zero: %w", errors.ErrInvalidParameter) } if serverId == "" { - return nil, nil, fmt.Errorf("activate session: missing server id: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("activate session: missing server id: %w", errors.ErrInvalidParameter) } if serverType == "" { - return nil, nil, fmt.Errorf("activate session: missing server type: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("activate session: missing server type: %w", errors.ErrInvalidParameter) } if len(tofuToken) == 0 { - return nil, nil, fmt.Errorf("activate session: missing tofu token: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("activate session: missing tofu token: %w", errors.ErrInvalidParameter) } updatedSession := AllocSession() @@ -614,7 +615,7 @@ func (r *Repository) ActivateSession(ctx context.Context, sessionId string, sess } if err == nil && rowsUpdated > 1 { // return err, which will result in a rollback of the update - return errors.New("error more than 1 session would have been updated ") + return stderrors.New("error more than 1 session would have been updated ") } returnedStates, err = fetchStates(ctx, reader, sessionId, db.WithOrder("start_time desc")) @@ -635,16 +636,16 @@ func (r *Repository) ActivateSession(ctx context.Context, sessionId string, sess // descending. No options are currently supported. func (r *Repository) updateState(ctx context.Context, sessionId string, sessionVersion uint32, s Status, opt ...Option) (*Session, []*State, error) { if sessionId == "" { - return nil, nil, fmt.Errorf("update session state: missing session id %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("update session state: missing session id %w", errors.ErrInvalidParameter) } if sessionVersion == 0 { - return nil, nil, fmt.Errorf("update session state: version cannot be zero: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("update session state: version cannot be zero: %w", errors.ErrInvalidParameter) } if s == "" { - return nil, nil, fmt.Errorf("update session state: missing session status: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("update session state: missing session status: %w", errors.ErrInvalidParameter) } if s == StatusActive { - return nil, nil, fmt.Errorf("update session: you must call ActivateSession to update a session's state to active: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("update session: you must call ActivateSession to update a session's state to active: %w", errors.ErrInvalidParameter) } var rowsAffected int diff --git a/internal/session/repository_session_test.go b/internal/session/repository_session_test.go index b50a942ce..2e24ea813 100644 --- a/internal/session/repository_session_test.go +++ b/internal/session/repository_session_test.go @@ -2,7 +2,6 @@ package session import ( "context" - "errors" "testing" "time" @@ -17,7 +16,9 @@ import ( targetStore "github.com/hashicorp/boundary/internal/target/store" "github.com/lib/pq" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" + iamStore "github.com/hashicorp/boundary/internal/iam/store" "github.com/hashicorp/boundary/internal/kms" @@ -203,7 +204,7 @@ func TestRepository_CreateSession(t *testing.T) { }(), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-hostId", @@ -215,7 +216,7 @@ func TestRepository_CreateSession(t *testing.T) { }(), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-targetId", @@ -227,7 +228,7 @@ func TestRepository_CreateSession(t *testing.T) { }(), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-hostSetId", @@ -239,7 +240,7 @@ func TestRepository_CreateSession(t *testing.T) { }(), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-authTokenId", @@ -251,7 +252,7 @@ func TestRepository_CreateSession(t *testing.T) { }(), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-scopeId", @@ -263,7 +264,7 @@ func TestRepository_CreateSession(t *testing.T) { }(), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -371,7 +372,7 @@ func TestRepository_updateState(t *testing.T) { return &v }(), wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "bad-sessionId", @@ -392,7 +393,7 @@ func TestRepository_updateState(t *testing.T) { return &s }(), wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -565,7 +566,7 @@ func TestRepository_ConnectConnection(t *testing.T) { return cw }(), wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-ClientTcpAddress", @@ -575,7 +576,7 @@ func TestRepository_ConnectConnection(t *testing.T) { return cw }(), wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-ClientTcpPort", @@ -585,7 +586,7 @@ func TestRepository_ConnectConnection(t *testing.T) { return cw }(), wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-EndpointTcpAddress", @@ -595,7 +596,7 @@ func TestRepository_ConnectConnection(t *testing.T) { return cw }(), wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-EndpointTcpPort", @@ -605,7 +606,7 @@ func TestRepository_ConnectConnection(t *testing.T) { return cw }(), wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -672,7 +673,7 @@ func TestRepository_TerminateSession(t *testing.T) { }(), reason: ClosedByUser, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-session-version", @@ -683,7 +684,7 @@ func TestRepository_TerminateSession(t *testing.T) { }(), reason: ClosedByUser, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "open-connection", @@ -999,7 +1000,7 @@ func TestRepository_CloseConnections(t *testing.T) { closeWith: []CloseWith{}, reason: ClosedByUser, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "missing-ConnectionId", @@ -1011,7 +1012,7 @@ func TestRepository_CloseConnections(t *testing.T) { }(), reason: ClosedByUser, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -1104,7 +1105,7 @@ func TestRepository_CancelSession(t *testing.T) { }(), wantStatus: StatusCanceling, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "bad-version-id", @@ -1125,7 +1126,7 @@ func TestRepository_CancelSession(t *testing.T) { }(), wantStatus: StatusCanceling, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -1413,7 +1414,7 @@ func TestRepository_ActivateSession(t *testing.T) { return &id }(), wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-session-version", @@ -1423,7 +1424,7 @@ func TestRepository_ActivateSession(t *testing.T) { return &v }(), wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -1531,7 +1532,7 @@ func TestRepository_DeleteSession(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantErrMsg: "delete session: failed record not found for ", + wantErrMsg: "delete session: failed record not found:", }, } for _, tt := range tests { @@ -1544,7 +1545,7 @@ func TestRepository_DeleteSession(t *testing.T) { assert.Contains(err.Error(), tt.wantErrMsg) err = db.TestVerifyOplog(t, rw, tt.args.session.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } assert.NoError(err) diff --git a/internal/session/session.go b/internal/session/session.go index 8de29b371..85d560c3c 100644 --- a/internal/session/session.go +++ b/internal/session/session.go @@ -13,6 +13,7 @@ import ( "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/db/timestamp" + "github.com/hashicorp/boundary/internal/errors" wrapping "github.com/hashicorp/go-kms-wrapping" "github.com/hashicorp/go-kms-wrapping/structwrapping" "google.golang.org/protobuf/types/known/timestamppb" @@ -200,7 +201,7 @@ func (s *Session) Clone() interface{} { func (s *Session) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { opts := db.GetOpts(opt...) if s.PublicId == "" { - return fmt.Errorf("session vet for write: missing public id: %w", db.ErrInvalidParameter) + return fmt.Errorf("session vet for write: missing public id: %w", errors.ErrInvalidParameter) } switch opType { case db.CreateOp: @@ -208,37 +209,37 @@ func (s *Session) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType return err } if len(s.Certificate) == 0 { - return fmt.Errorf("session vet for write: certificate is missing: %w", db.ErrInvalidParameter) + return fmt.Errorf("session vet for write: certificate is missing: %w", errors.ErrInvalidParameter) } case db.UpdateOp: switch { case contains(opts.WithFieldMaskPaths, "PublicId"): - return fmt.Errorf("session vet for write: public id is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("session vet for write: public id is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "UserId"): - return fmt.Errorf("session vet for write: user id is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("session vet for write: user id is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "HostId"): - return fmt.Errorf("session vet for write: host id is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("session vet for write: host id is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "TargetId"): - return fmt.Errorf("session vet for write: target id is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("session vet for write: target id is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "HostSetId"): - return fmt.Errorf("session vet for write: host set id is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("session vet for write: host set id is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "AuthTokenId"): - return fmt.Errorf("session vet for write: auth token id is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("session vet for write: auth token id is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "Certificate"): - return fmt.Errorf("session vet for write: certificate is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("session vet for write: certificate is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "CreateTime"): - return fmt.Errorf("session vet for write: create time is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("session vet for write: create time is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "UpdateTime"): - return fmt.Errorf("session vet for write: update time is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("session vet for write: update time is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "Endpoint"): - return fmt.Errorf("session vet for write: endpoint is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("session vet for write: endpoint is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "ExpirationTime"): - return fmt.Errorf("session vet for write: expiration time is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("session vet for write: expiration time is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "ConnectionLimit"): - return fmt.Errorf("session vet for write: connection limit is immutable: %w", db.ErrInvalidParameter) + return fmt.Errorf("session vet for write: connection limit is immutable: %w", errors.ErrInvalidParameter) case contains(opts.WithFieldMaskPaths, "TerminationReason"): if _, err := convertToReason(s.TerminationReason); err != nil { - return fmt.Errorf("session vet for write: termination reason '%s' is invalid: %w", s.TerminationReason, db.ErrInvalidParameter) + return fmt.Errorf("session vet for write: termination reason '%s' is invalid: %w", s.TerminationReason, errors.ErrInvalidParameter) } } } @@ -263,43 +264,43 @@ func (s *Session) SetTableName(n string) { // validateNewSession checks everything but the session's PublicId func (s *Session) validateNewSession(errorPrefix string) error { if s.UserId == "" { - return fmt.Errorf("%s missing user id: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing user id: %w", errorPrefix, errors.ErrInvalidParameter) } if s.HostId == "" { - return fmt.Errorf("%s missing host id: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing host id: %w", errorPrefix, errors.ErrInvalidParameter) } if s.TargetId == "" { - return fmt.Errorf("%s missing target id: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing target id: %w", errorPrefix, errors.ErrInvalidParameter) } if s.HostSetId == "" { - return fmt.Errorf("%s missing host set id: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing host set id: %w", errorPrefix, errors.ErrInvalidParameter) } if s.AuthTokenId == "" { - return fmt.Errorf("%s missing auth token id: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing auth token id: %w", errorPrefix, errors.ErrInvalidParameter) } if s.ScopeId == "" { - return fmt.Errorf("%s missing scope id: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing scope id: %w", errorPrefix, errors.ErrInvalidParameter) } if s.Endpoint == "" { - return fmt.Errorf("%s missing endpoint: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing endpoint: %w", errorPrefix, errors.ErrInvalidParameter) } if s.ExpirationTime.GetTimestamp().AsTime().IsZero() { - return fmt.Errorf("%s missing expiration time: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing expiration time: %w", errorPrefix, errors.ErrInvalidParameter) } if s.TerminationReason != "" { - return fmt.Errorf("%s termination reason must be empty: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s termination reason must be empty: %w", errorPrefix, errors.ErrInvalidParameter) } if s.ServerId != "" { - return fmt.Errorf("%s server id must be empty: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s server id must be empty: %w", errorPrefix, errors.ErrInvalidParameter) } if s.ServerType != "" { - return fmt.Errorf("%s server type must be empty: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s server type must be empty: %w", errorPrefix, errors.ErrInvalidParameter) } if s.TofuToken != nil { - return fmt.Errorf("%s tofu token must be empty: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s tofu token must be empty: %w", errorPrefix, errors.ErrInvalidParameter) } if s.CtTofuToken != nil { - return fmt.Errorf("%s ct must be empty: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s ct must be empty: %w", errorPrefix, errors.ErrInvalidParameter) } return nil } @@ -315,13 +316,13 @@ func contains(ss []string, t string) bool { func newCert(wrapper wrapping.Wrapper, userId, jobId string, exp time.Time) (ed25519.PrivateKey, []byte, error) { if wrapper == nil { - return nil, nil, fmt.Errorf("new session cert: missing wrapper: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("new session cert: missing wrapper: %w", errors.ErrInvalidParameter) } if userId == "" { - return nil, nil, fmt.Errorf("new session cert: missing user id: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("new session cert: missing user id: %w", errors.ErrInvalidParameter) } if jobId == "" { - return nil, nil, fmt.Errorf("new session cert: missing job id: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("new session cert: missing job id: %w", errors.ErrInvalidParameter) } pubKey, privKey, err := DeriveED25519Key(wrapper, userId, jobId) if err != nil { diff --git a/internal/session/session_connect_with.go b/internal/session/session_connect_with.go index 584b94b9c..9fe5385d6 100644 --- a/internal/session/session_connect_with.go +++ b/internal/session/session_connect_with.go @@ -3,7 +3,7 @@ package session import ( "fmt" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" ) // ConnectWith defines the boundary data that is saved in the repo when the @@ -18,19 +18,19 @@ type ConnectWith struct { func (c ConnectWith) validate() error { if c.ConnectionId == "" { - return fmt.Errorf("missing session id: %w", db.ErrInvalidParameter) + return fmt.Errorf("missing session id: %w", errors.ErrInvalidParameter) } if c.ClientTcpAddress == "" { - return fmt.Errorf("missing client tcp address: %w", db.ErrInvalidParameter) + return fmt.Errorf("missing client tcp address: %w", errors.ErrInvalidParameter) } if c.ClientTcpPort == 0 { - return fmt.Errorf("missing client ctp port: %w", db.ErrInvalidParameter) + return fmt.Errorf("missing client ctp port: %w", errors.ErrInvalidParameter) } if c.EndpointTcpAddress == "" { - return fmt.Errorf("missing endpoint tcp address: %w", db.ErrInvalidParameter) + return fmt.Errorf("missing endpoint tcp address: %w", errors.ErrInvalidParameter) } if c.EndpointTcpPort == 0 { - return fmt.Errorf("missing endpoint ctp port: %w", db.ErrInvalidParameter) + return fmt.Errorf("missing endpoint ctp port: %w", errors.ErrInvalidParameter) } return nil } diff --git a/internal/session/session_test.go b/internal/session/session_test.go index ddb83600a..06215830b 100644 --- a/internal/session/session_test.go +++ b/internal/session/session_test.go @@ -2,13 +2,13 @@ package session import ( "context" - "errors" "testing" "time" "github.com/golang/protobuf/ptypes" "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/db/timestamp" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -67,7 +67,7 @@ func TestSession_Create(t *testing.T) { }(), }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-hostId", @@ -79,7 +79,7 @@ func TestSession_Create(t *testing.T) { }(), }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-targetId", @@ -91,7 +91,7 @@ func TestSession_Create(t *testing.T) { }(), }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-hostSetId", @@ -103,7 +103,7 @@ func TestSession_Create(t *testing.T) { }(), }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-authTokenId", @@ -115,7 +115,7 @@ func TestSession_Create(t *testing.T) { }(), }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-scopeId", @@ -127,7 +127,7 @@ func TestSession_Create(t *testing.T) { }(), }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -213,7 +213,7 @@ func TestSession_Delete(t *testing.T) { foundSession.PublicId = tt.session.PublicId err = rw.LookupById(context.Background(), &foundSession) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/session/state.go b/internal/session/state.go index b943f0f63..f3e0197fb 100644 --- a/internal/session/state.go +++ b/internal/session/state.go @@ -6,6 +6,7 @@ import ( "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/db/timestamp" + "github.com/hashicorp/boundary/internal/errors" "google.golang.org/protobuf/types/known/timestamppb" workerpbs "github.com/hashicorp/boundary/internal/gen/controller/servers/services" @@ -144,19 +145,19 @@ func (s *State) SetTableName(n string) { // validate checks the session state func (s *State) validate(errorPrefix string) error { if s.Status == "" { - return fmt.Errorf("%s missing status: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing status: %w", errorPrefix, errors.ErrInvalidParameter) } if s.SessionId == "" { - return fmt.Errorf("%s missing session id: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s missing session id: %w", errorPrefix, errors.ErrInvalidParameter) } if s.StartTime != nil { - return fmt.Errorf("%s start time is not settable: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s start time is not settable: %w", errorPrefix, errors.ErrInvalidParameter) } if s.EndTime != nil { - return fmt.Errorf("%s end time is not settable: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s end time is not settable: %w", errorPrefix, errors.ErrInvalidParameter) } if s.PreviousEndTime != nil { - return fmt.Errorf("%s previous end time is not settable: %w", errorPrefix, db.ErrInvalidParameter) + return fmt.Errorf("%s previous end time is not settable: %w", errorPrefix, errors.ErrInvalidParameter) } return nil } diff --git a/internal/session/state_test.go b/internal/session/state_test.go index 272525bde..ed52c50c9 100644 --- a/internal/session/state_test.go +++ b/internal/session/state_test.go @@ -2,10 +2,10 @@ package session import ( "context" - "errors" "testing" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -49,7 +49,7 @@ func TestState_Create(t *testing.T) { status: StatusPending, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "empty-status", @@ -57,7 +57,7 @@ func TestState_Create(t *testing.T) { sessionId: session.PublicId, }, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -148,7 +148,7 @@ func TestState_Delete(t *testing.T) { foundState := allocState() err = rw.LookupWhere(context.Background(), &foundState, "session_id = ? and start_time = ?", tt.state.SessionId, initialState.StartTime) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } diff --git a/internal/session/term_reason.go b/internal/session/term_reason.go index b8e21809c..41450f25f 100644 --- a/internal/session/term_reason.go +++ b/internal/session/term_reason.go @@ -3,7 +3,7 @@ package session import ( "fmt" - "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" ) // TerminationReason of the session @@ -41,6 +41,6 @@ func convertToReason(s string) (TerminationReason, error) { case ConnectionLimit.String(): return ConnectionLimit, nil default: - return "", fmt.Errorf("termination reason: %s is not a valid reason: %w", s, db.ErrInvalidParameter) + return "", fmt.Errorf("termination reason: %s is not a valid reason: %w", s, errors.ErrInvalidParameter) } } diff --git a/internal/target/repository.go b/internal/target/repository.go index b21c58548..54956ece7 100644 --- a/internal/target/repository.go +++ b/internal/target/repository.go @@ -2,17 +2,18 @@ package target import ( "context" - "errors" + stderrors "errors" "fmt" "strings" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/oplog" ) var ( - ErrMetadataScopeNotFound = errors.New("scope not found for metadata") + ErrMetadataScopeNotFound = stderrors.New("scope not found for metadata") ) // Clonable provides a cloning interface @@ -34,13 +35,13 @@ type Repository struct { // which sets a default limit on results returned by repo operations. func NewRepository(r db.Reader, w db.Writer, kms *kms.Kms, opt ...Option) (*Repository, error) { if r == nil { - return nil, errors.New("error creating db repository with nil reader") + return nil, stderrors.New("error creating db repository with nil reader") } if w == nil { - return nil, errors.New("error creating db repository with nil writer") + return nil, stderrors.New("error creating db repository with nil writer") } if kms == nil { - return nil, errors.New("error creating db repository with nil kms") + return nil, stderrors.New("error creating db repository with nil kms") } opts := getOpts(opt...) if opts.withLimit == 0 { @@ -62,7 +63,7 @@ func (r *Repository) LookupTarget(ctx context.Context, publicIdOrName string, op opts := getOpts(opt...) if publicIdOrName == "" { - return nil, nil, fmt.Errorf("lookup target: missing private id: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("lookup target: missing private id: %w", errors.ErrInvalidParameter) } var where []string @@ -72,27 +73,27 @@ func (r *Repository) LookupTarget(ctx context.Context, publicIdOrName string, op scopeNameEmpty := opts.withScopeName == "" if !nameEmpty { if opts.withName != publicIdOrName { - return nil, nil, fmt.Errorf("lookup target: name passed in but does not match publicId: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("lookup target: name passed in but does not match publicId: %w", errors.ErrInvalidParameter) } where, whereArgs = append(where, "lower(name) = lower(?)"), append(whereArgs, opts.withName) switch { case scopeIdEmpty && scopeNameEmpty: - return nil, nil, fmt.Errorf("lookup target: using name but both scope ID and scope name are empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("lookup target: using name but both scope ID and scope name are empty: %w", errors.ErrInvalidParameter) case !scopeIdEmpty && !scopeNameEmpty: - return nil, nil, fmt.Errorf("lookup target: using name but both scope ID and scope name are set: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("lookup target: using name but both scope ID and scope name are set: %w", errors.ErrInvalidParameter) case !scopeIdEmpty: where, whereArgs = append(where, "scope_id = ?"), append(whereArgs, opts.withScopeId) case !scopeNameEmpty: where, whereArgs = append(where, "scope_id = (select public_id from iam_scope where lower(name) = lower(?))"), append(whereArgs, opts.withScopeName) default: - return nil, nil, fmt.Errorf("lookup target: unknown combination of parameters: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("lookup target: unknown combination of parameters: %w", errors.ErrInvalidParameter) } } else { switch { case !scopeIdEmpty: - return nil, nil, fmt.Errorf("lookup target: passed in scope ID when using target ID for lookup: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("lookup target: passed in scope ID when using target ID for lookup: %w", errors.ErrInvalidParameter) case !scopeNameEmpty: - return nil, nil, fmt.Errorf("lookup target: passed in scope name when using target ID for lookup: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("lookup target: passed in scope name when using target ID for lookup: %w", errors.ErrInvalidParameter) } } @@ -123,7 +124,7 @@ func (r *Repository) LookupTarget(ctx context.Context, publicIdOrName string, op }, ) if err != nil { - if errors.Is(err, db.ErrRecordNotFound) { + if errors.Is(err, errors.ErrRecordNotFound) { return nil, nil, nil } return nil, nil, fmt.Errorf("lookup target: %w", err) @@ -150,7 +151,7 @@ func fetchSets(ctx context.Context, r db.Reader, targetId string) ([]*TargetSet, func (r *Repository) ListTargets(ctx context.Context, opt ...Option) ([]Target, error) { opts := getOpts(opt...) if opts.withScopeId == "" && opts.withUserId == "" { - return nil, fmt.Errorf("list targets: must specify either a scope id or user id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("list targets: must specify either a scope id or user id: %w", errors.ErrInvalidParameter) } // TODO (jimlambrt 8/2020) - implement WithUserId() optional filtering. var where []string @@ -197,7 +198,7 @@ func (r *Repository) list(ctx context.Context, resources interface{}, where stri // DeleteTarget will delete a target from the repository. func (r *Repository) DeleteTarget(ctx context.Context, publicId string, opt ...Option) (int, error) { if publicId == "" { - return db.NoRowsAffected, fmt.Errorf("delete target: missing public id %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete target: missing public id %w", errors.ErrInvalidParameter) } t := allocTargetView() t.PublicId = publicId @@ -236,7 +237,7 @@ func (r *Repository) DeleteTarget(ctx context.Context, publicId string, opt ...O ) if err == nil && rowsDeleted > 1 { // return err, which will result in a rollback of the delete - return db.ErrMultipleRecords + return errors.ErrMultipleRecords } return err }, @@ -248,14 +249,14 @@ func (r *Repository) DeleteTarget(ctx context.Context, publicId string, opt ...O // It currently supports no options. func (r *Repository) update(ctx context.Context, target Target, version uint32, fieldMaskPaths []string, setToNullPaths []string, opt ...Option) (Target, []*TargetSet, int, error) { if version == 0 { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update: version cannot be zero: %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update: version cannot be zero: %w", errors.ErrInvalidParameter) } if target == nil { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update: target is nil: %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update: target is nil: %w", errors.ErrInvalidParameter) } cloner, ok := target.(Cloneable) if !ok { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update: target is not Cloneable: %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update: target is not Cloneable: %w", errors.ErrInvalidParameter) } dbOpts := []db.Option{ db.WithVersion(&version), @@ -297,7 +298,7 @@ func (r *Repository) update(ctx context.Context, target Target, version uint32, } if err == nil && rowsUpdated > 1 { // return err, which will result in a rollback of the update - return fmt.Errorf("error more than 1 target would have been updated: %w", db.ErrMultipleRecords) + return fmt.Errorf("error more than 1 target would have been updated: %w", errors.ErrMultipleRecords) } var err error if hostSets, err = fetchSets(ctx, reader, target.GetPublicId()); err != nil { @@ -316,13 +317,13 @@ func (r *Repository) update(ctx context.Context, target Target, version uint32, // for the WithVersion option and will return an error. func (r *Repository) AddTargetHostSets(ctx context.Context, targetId string, targetVersion uint32, hostSetIds []string, opt ...Option) (Target, []*TargetSet, error) { if targetId == "" { - return nil, nil, fmt.Errorf("add target host sets: missing target id: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("add target host sets: missing target id: %w", errors.ErrInvalidParameter) } if targetVersion == 0 { - return nil, nil, fmt.Errorf("add target host sets: version cannot be zero: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("add target host sets: version cannot be zero: %w", errors.ErrInvalidParameter) } if len(hostSetIds) == 0 { - return nil, nil, fmt.Errorf("add target host sets: missing host set ids: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("add target host sets: missing host set ids: %w", errors.ErrInvalidParameter) } newHostSets := make([]interface{}, 0, len(hostSetIds)) for _, id := range hostSetIds { @@ -405,13 +406,13 @@ func (r *Repository) AddTargetHostSets(ctx context.Context, targetId string, tar // error. func (r *Repository) DeleteTargeHostSets(ctx context.Context, targetId string, targetVersion uint32, hostSetIds []string, opt ...Option) (int, error) { if targetId == "" { - return db.NoRowsAffected, fmt.Errorf("delete target host sets: missing target id: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete target host sets: missing target id: %w", errors.ErrInvalidParameter) } if targetVersion == 0 { - return db.NoRowsAffected, fmt.Errorf("delete target host sets: version cannot be zero: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete target host sets: version cannot be zero: %w", errors.ErrInvalidParameter) } if len(hostSetIds) == 0 { - return db.NoRowsAffected, fmt.Errorf("delete target host sets: missing host set ids: %w", db.ErrInvalidParameter) + return db.NoRowsAffected, fmt.Errorf("delete target host sets: missing host set ids: %w", errors.ErrInvalidParameter) } deleteTargeHostSets := make([]interface{}, 0, len(hostSetIds)) for _, id := range hostSetIds { @@ -497,10 +498,10 @@ func (r *Repository) DeleteTargeHostSets(ctx context.Context, targetId string, t // is not a valid value for the WithVersion option and will return an error. func (r *Repository) SetTargetHostSets(ctx context.Context, targetId string, targetVersion uint32, hostSetIds []string, opt ...Option) ([]*TargetSet, int, error) { if targetId == "" { - return nil, db.NoRowsAffected, fmt.Errorf("set target host sets: missing target id: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("set target host sets: missing target id: %w", errors.ErrInvalidParameter) } if targetVersion == 0 { - return nil, db.NoRowsAffected, fmt.Errorf("set target host sets: version cannot be zero: %w", db.ErrInvalidParameter) + return nil, db.NoRowsAffected, fmt.Errorf("set target host sets: version cannot be zero: %w", errors.ErrInvalidParameter) } t := allocTargetView() t.PublicId = targetId diff --git a/internal/target/repository_tcp_target.go b/internal/target/repository_tcp_target.go index bd9e7a165..39a35b369 100644 --- a/internal/target/repository_tcp_target.go +++ b/internal/target/repository_tcp_target.go @@ -6,6 +6,7 @@ import ( "strings" dbcommon "github.com/hashicorp/boundary/internal/db/common" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/kms" @@ -17,26 +18,26 @@ import ( func (r *Repository) CreateTcpTarget(ctx context.Context, target *TcpTarget, opt ...Option) (Target, []*TargetSet, error) { opts := getOpts(opt...) if target == nil { - return nil, nil, fmt.Errorf("create tcp target: missing target: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create tcp target: missing target: %w", errors.ErrInvalidParameter) } if target.TcpTarget == nil { - return nil, nil, fmt.Errorf("create tcp target: missing target store: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create tcp target: missing target store: %w", errors.ErrInvalidParameter) } if target.ScopeId == "" { - return nil, nil, fmt.Errorf("create tcp target: scope id empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create tcp target: scope id empty: %w", errors.ErrInvalidParameter) } if target.Name == "" { - return nil, nil, fmt.Errorf("create tcp target: name empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create tcp target: name empty: %w", errors.ErrInvalidParameter) } if target.PublicId != "" { - return nil, nil, fmt.Errorf("create tcp target: public id not empty: %w", db.ErrInvalidParameter) + return nil, nil, fmt.Errorf("create tcp target: public id not empty: %w", errors.ErrInvalidParameter) } t := target.Clone().(*TcpTarget) if opts.withPublicId != "" { if !strings.HasPrefix(opts.withPublicId, TcpTargetPrefix+"_") { - return nil, nil, fmt.Errorf("create tcp target: passed-in public ID %q has wrong prefix, should be %q: %w", opts.withPublicId, TcpTargetPrefix, db.ErrInvalidPublicId) + return nil, nil, fmt.Errorf("create tcp target: passed-in public ID %q has wrong prefix, should be %q: %w", opts.withPublicId, TcpTargetPrefix, errors.ErrInvalidPublicId) } t.PublicId = opts.withPublicId } else { @@ -112,13 +113,13 @@ func (r *Repository) CreateTcpTarget(ctx context.Context, target *TcpTarget, opt // returned. func (r *Repository) UpdateTcpTarget(ctx context.Context, target *TcpTarget, version uint32, fieldMaskPaths []string, opt ...Option) (Target, []*TargetSet, int, error) { if target == nil { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update tcp target: missing target %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update tcp target: missing target %w", errors.ErrInvalidParameter) } if target.TcpTarget == nil { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update tcp target: missing target store %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update tcp target: missing target store %w", errors.ErrInvalidParameter) } if target.PublicId == "" { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update tcp target: missing target public id %w", db.ErrInvalidParameter) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update tcp target: missing target public id %w", errors.ErrInvalidParameter) } for _, f := range fieldMaskPaths { switch { @@ -128,7 +129,7 @@ func (r *Repository) UpdateTcpTarget(ctx context.Context, target *TcpTarget, ver case strings.EqualFold("sessionmaxseconds", f): case strings.EqualFold("sessionconnectionlimit", f): default: - return nil, nil, db.NoRowsAffected, fmt.Errorf("update tcp target: field: %s: %w", f, db.ErrInvalidFieldMask) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update tcp target: field: %s: %w", f, errors.ErrInvalidFieldMask) } } var dbMask, nullFields []string @@ -144,7 +145,7 @@ func (r *Repository) UpdateTcpTarget(ctx context.Context, target *TcpTarget, ver []string{"SessionMaxSeconds", "SessionConnectionLimit"}, ) if len(dbMask) == 0 && len(nullFields) == 0 { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update tcp target: %w", db.ErrEmptyFieldMask) + return nil, nil, db.NoRowsAffected, fmt.Errorf("update tcp target: %w", errors.ErrEmptyFieldMask) } var returnedTarget Target var rowsUpdated int @@ -164,8 +165,8 @@ func (r *Repository) UpdateTcpTarget(ctx context.Context, target *TcpTarget, ver }, ) if err != nil { - if db.IsUniqueError(err) { - return nil, nil, db.NoRowsAffected, fmt.Errorf("update tcp target: target %s already exists in scope %s: %w", target.Name, target.ScopeId, db.ErrNotUnique) + if errors.IsUniqueError(err) { + return nil, nil, db.NoRowsAffected, fmt.Errorf("update tcp target: target %s already exists in scope %s: %w", target.Name, target.ScopeId, errors.ErrNotUnique) } return nil, nil, db.NoRowsAffected, fmt.Errorf("update tcp target: %w for %s", err, target.PublicId) } diff --git a/internal/target/repository_tcp_target_test.go b/internal/target/repository_tcp_target_test.go index 7449b9d1c..b7f097e2a 100644 --- a/internal/target/repository_tcp_target_test.go +++ b/internal/target/repository_tcp_target_test.go @@ -2,12 +2,12 @@ package target import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/db" dbassert "github.com/hashicorp/boundary/internal/db/assert" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/host/static" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" @@ -67,7 +67,7 @@ func TestRepository_CreateTcpTarget(t *testing.T) { target: nil, }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "nil-target-store", @@ -78,7 +78,7 @@ func TestRepository_CreateTcpTarget(t *testing.T) { }(), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "public-id-not-empty", @@ -93,7 +93,7 @@ func TestRepository_CreateTcpTarget(t *testing.T) { }(), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, { name: "empty-scope-id", @@ -106,7 +106,7 @@ func TestRepository_CreateTcpTarget(t *testing.T) { }(), }, wantErr: true, - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, }, } for _, tt := range tests { @@ -219,8 +219,8 @@ func TestRepository_UpdateTcpTarget(t *testing.T) { newScopeId: proj.PublicId, wantErr: true, wantRowsUpdate: 0, - wantErrMsg: "update tcp target: update: lookup after write: record not found for 1", - wantIsError: db.ErrRecordNotFound, + wantErrMsg: "update tcp target: update: lookup after write: record not found", + wantIsError: errors.ErrRecordNotFound, }, { name: "null-name", @@ -258,7 +258,7 @@ func TestRepository_UpdateTcpTarget(t *testing.T) { wantErr: true, wantRowsUpdate: 0, wantErrMsg: "update tcp target: empty field mask", - wantIsError: db.ErrEmptyFieldMask, + wantIsError: errors.ErrEmptyFieldMask, }, { name: "nil-fieldmask", @@ -271,7 +271,7 @@ func TestRepository_UpdateTcpTarget(t *testing.T) { wantErr: true, wantRowsUpdate: 0, wantErrMsg: "update tcp target: empty field mask", - wantIsError: db.ErrEmptyFieldMask, + wantIsError: errors.ErrEmptyFieldMask, }, { name: "read-only-fields", @@ -284,7 +284,7 @@ func TestRepository_UpdateTcpTarget(t *testing.T) { wantErr: true, wantRowsUpdate: 0, wantErrMsg: "update tcp target: field: CreateTime: invalid field mask", - wantIsError: db.ErrInvalidFieldMask, + wantIsError: errors.ErrInvalidFieldMask, }, { name: "unknown-fields", @@ -297,7 +297,7 @@ func TestRepository_UpdateTcpTarget(t *testing.T) { wantErr: true, wantRowsUpdate: 0, wantErrMsg: "update tcp target: field: Alice: invalid field mask", - wantIsError: db.ErrInvalidFieldMask, + wantIsError: errors.ErrInvalidFieldMask, }, { name: "no-public-id", @@ -310,7 +310,7 @@ func TestRepository_UpdateTcpTarget(t *testing.T) { newScopeId: proj.PublicId, wantErr: true, wantErrMsg: "update tcp target: missing target public id invalid parameter", - wantIsError: db.ErrInvalidParameter, + wantIsError: errors.ErrInvalidParameter, wantRowsUpdate: 0, }, { @@ -322,7 +322,7 @@ func TestRepository_UpdateTcpTarget(t *testing.T) { newScopeId: proj.PublicId, wantErr: true, wantErrMsg: "update tcp target: empty field mask", - wantIsError: db.ErrEmptyFieldMask, + wantIsError: errors.ErrEmptyFieldMask, }, { name: "empty-scope-id-with-name-mask", @@ -346,7 +346,7 @@ func TestRepository_UpdateTcpTarget(t *testing.T) { wantErr: true, wantDup: true, wantErrMsg: " already exists in scope " + proj.PublicId, - wantIsError: db.ErrNotUnique, + wantIsError: errors.ErrNotUnique, }, } for _, tt := range tests { @@ -389,7 +389,7 @@ func TestRepository_UpdateTcpTarget(t *testing.T) { assert.Contains(err.Error(), tt.wantErrMsg) err = db.TestVerifyOplog(t, rw, target.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) diff --git a/internal/target/repository_test.go b/internal/target/repository_test.go index 44176c37a..c943e8cf3 100644 --- a/internal/target/repository_test.go +++ b/internal/target/repository_test.go @@ -2,13 +2,13 @@ package target import ( "context" - "errors" "sort" "strconv" "testing" "time" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/host/static" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" @@ -373,7 +373,7 @@ func TestRepository_DeleteTarget(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantErrMsg: "delete target: failed record not found for ", + wantErrMsg: "delete target: failed record not found:", }, } for _, tt := range tests { @@ -386,7 +386,7 @@ func TestRepository_DeleteTarget(t *testing.T) { assert.Contains(err.Error(), tt.wantErrMsg) err = db.TestVerifyOplog(t, rw, tt.args.target.GetPublicId(), db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } assert.NoError(err) @@ -595,7 +595,7 @@ func TestRepository_DeleteTargetHosts(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "not-found", @@ -618,7 +618,7 @@ func TestRepository_DeleteTargetHosts(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "zero-version", @@ -630,7 +630,7 @@ func TestRepository_DeleteTargetHosts(t *testing.T) { }, wantRowsDeleted: 0, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "bad-version", @@ -694,7 +694,7 @@ func TestRepository_DeleteTargetHosts(t *testing.T) { err = db.TestVerifyOplog(t, rw, tt.args.target.GetPublicId(), db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) assert.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) return } require.NoError(err) diff --git a/internal/target/target_host_set.go b/internal/target/target_host_set.go index 85f714a75..ef8631c29 100644 --- a/internal/target/target_host_set.go +++ b/internal/target/target_host_set.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" hostStore "github.com/hashicorp/boundary/internal/host/store" "github.com/hashicorp/boundary/internal/oplog" "github.com/hashicorp/boundary/internal/target/store" @@ -26,10 +27,10 @@ var _ db.VetForWriter = (*TargetHostSet)(nil) // currently supported. func NewTargetHostSet(targetId, hostSetId string, opt ...Option) (*TargetHostSet, error) { if targetId == "" { - return nil, fmt.Errorf("new target host set: missing target id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new target host set: missing target id: %w", errors.ErrInvalidParameter) } if hostSetId == "" { - return nil, fmt.Errorf("new target host set: missing hostSetId id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new target host set: missing hostSetId id: %w", errors.ErrInvalidParameter) } t := &TargetHostSet{ TargetHostSet: &store.TargetHostSet{ @@ -60,10 +61,10 @@ func (t *TargetHostSet) Clone() interface{} { func (t *TargetHostSet) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if opType == db.CreateOp { if t.TargetId == "" { - return fmt.Errorf("target host set: vet for write: missing target id: %w", db.ErrInvalidParameter) + return fmt.Errorf("target host set: vet for write: missing target id: %w", errors.ErrInvalidParameter) } if t.HostSetId == "" { - return fmt.Errorf("target host set: vet for write: missing host set id: %w", db.ErrInvalidParameter) + return fmt.Errorf("target host set: vet for write: missing host set id: %w", errors.ErrInvalidParameter) } } return nil diff --git a/internal/target/tcp_target.go b/internal/target/tcp_target.go index 8f3c47a09..ef5493168 100644 --- a/internal/target/tcp_target.go +++ b/internal/target/tcp_target.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/oplog" "github.com/hashicorp/boundary/internal/target/store" "google.golang.org/protobuf/proto" @@ -28,7 +29,7 @@ var _ oplog.ReplayableMessage = (*TcpTarget)(nil) func NewTcpTarget(scopeId string, opt ...Option) (*TcpTarget, error) { opts := getOpts(opt...) if scopeId == "" { - return nil, fmt.Errorf("new tcp target: missing scope id: %w", db.ErrInvalidParameter) + return nil, fmt.Errorf("new tcp target: missing scope id: %w", errors.ErrInvalidParameter) } t := &TcpTarget{ TcpTarget: &store.TcpTarget{ @@ -62,14 +63,14 @@ func (t *TcpTarget) Clone() interface{} { // before it's written. func (t *TcpTarget) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { if t.PublicId == "" { - return fmt.Errorf("tcp target vet for write: missing public id: %w", db.ErrInvalidParameter) + return fmt.Errorf("tcp target vet for write: missing public id: %w", errors.ErrInvalidParameter) } if opType == db.CreateOp { if t.ScopeId == "" { - return fmt.Errorf("tcp target vet for write: missing scope id: %w", db.ErrInvalidParameter) + return fmt.Errorf("tcp target vet for write: missing scope id: %w", errors.ErrInvalidParameter) } if t.Name == "" { - return fmt.Errorf("tcp target vet for write: missing name id: %w", db.ErrInvalidParameter) + return fmt.Errorf("tcp target vet for write: missing name id: %w", errors.ErrInvalidParameter) } } return nil diff --git a/internal/target/tcp_target_test.go b/internal/target/tcp_target_test.go index 68582af7f..da63a8207 100644 --- a/internal/target/tcp_target_test.go +++ b/internal/target/tcp_target_test.go @@ -2,12 +2,12 @@ package target import ( "context" - "errors" "testing" "time" "github.com/hashicorp/boundary/internal/db" dbassert "github.com/hashicorp/boundary/internal/db/assert" + "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/oplog" "github.com/stretchr/testify/assert" @@ -37,7 +37,7 @@ func TestTcpTarget_Create(t *testing.T) { name: "empty-scopeId", args: args{}, wantErr: true, - wantIsErr: db.ErrInvalidParameter, + wantIsErr: errors.ErrInvalidParameter, }, { name: "valid-proj-scope", @@ -138,7 +138,7 @@ func TestTcpTarget_Delete(t *testing.T) { foundTarget.PublicId = tt.target.PublicId err = rw.LookupById(context.Background(), &foundTarget) require.Error(err) - assert.True(errors.Is(db.ErrRecordNotFound, err)) + assert.True(errors.Is(errors.ErrRecordNotFound, err)) }) } } @@ -267,7 +267,7 @@ func TestTcpTarget_Update(t *testing.T) { assert.Equal(tt.wantErrMsg, err.Error()) err = db.TestVerifyOplog(t, rw, target.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) require.Error(err) - assert.Equal("record not found", err.Error()) + assert.Contains(err.Error(), "record not found:") return } require.NoError(err)