Remove sentinel errors (#968)

* Remove sentinal errors
This commit is contained in:
Louis Ruch authored and GitHub committed 2021-03-05 06:34:06 -08:00
1 parent 3b452cb503
commit 7387cec475
26 files changed
+210 -303

No files matched your search

+22 -7
View File
@@ -43,14 +43,29 @@ func NewArgon2Configuration() *Argon2Configuration {
}
func (c *Argon2Configuration) validate() error {
switch {
case c == nil, c.Argon2Configuration == nil:
return ErrInvalidConfiguration
case c.Iterations == 0, c.Memory == 0, c.Threads == 0, c.SaltLength == 0, c.KeyLength == 0:
return ErrInvalidConfiguration
default:
return nil
const op = "password.(Argon2Configuration).validate"
if c == nil {
return errors.New(errors.PasswordInvalidConfiguration, op, "missing config")
}
if c.Argon2Configuration == nil {
return errors.New(errors.PasswordInvalidConfiguration, op, "missing embedded config")
}
if c.Iterations == 0 {
return errors.New(errors.PasswordInvalidConfiguration, op, "missing iterations")
}
if c.Memory == 0 {
return errors.New(errors.PasswordInvalidConfiguration, op, "missing memory")
}
if c.Threads == 0 {
return errors.New(errors.PasswordInvalidConfiguration, op, "missing threads")
}
if c.SaltLength == 0 {
return errors.New(errors.PasswordInvalidConfiguration, op, "missing salt length")
}
if c.KeyLength == 0 {
return errors.New(errors.PasswordInvalidConfiguration, op, "missing key length")
}
return nil
}
// AuthMethodId returns the Id of the AuthMethod which owns c.
+29 -12
View File
@@ -163,17 +163,23 @@ func TestArgon2Configuration_Validate(t *testing.T) {
tests := []struct {
name string
in *Argon2Configuration
want error
wantErr bool
wantErrIs errors.Code
wantErrMsg string
}{
{
name: "nil-configuration",
in: nil,
want: ErrInvalidConfiguration,
wantErr: true,
wantErrIs: errors.PasswordInvalidConfiguration,
wantErrMsg: "password.(Argon2Configuration).validate: missing config: password violation: error #202",
},
{
name: "nil-embedded-config",
in: &Argon2Configuration{},
want: ErrInvalidConfiguration,
wantErr: true,
wantErrIs: errors.PasswordInvalidConfiguration,
wantErrMsg: "password.(Argon2Configuration).validate: missing embedded config: password violation: error #202",
},
{
name: "valid-default",
@@ -202,7 +208,9 @@ func TestArgon2Configuration_Validate(t *testing.T) {
KeyLength: 1,
},
},
want: ErrInvalidConfiguration,
wantErr: true,
wantErrIs: errors.PasswordInvalidConfiguration,
wantErrMsg: "password.(Argon2Configuration).validate: missing iterations: password violation: error #202",
},
{
name: "invalid-memory",
@@ -215,7 +223,9 @@ func TestArgon2Configuration_Validate(t *testing.T) {
KeyLength: 1,
},
},
want: ErrInvalidConfiguration,
wantErr: true,
wantErrIs: errors.PasswordInvalidConfiguration,
wantErrMsg: "password.(Argon2Configuration).validate: missing memory: password violation: error #202",
},
{
name: "invalid-threads",
@@ -228,7 +238,9 @@ func TestArgon2Configuration_Validate(t *testing.T) {
KeyLength: 1,
},
},
want: ErrInvalidConfiguration,
wantErr: true,
wantErrIs: errors.PasswordInvalidConfiguration,
wantErrMsg: "password.(Argon2Configuration).validate: missing threads: password violation: error #202",
},
{
name: "invalid-salt-length",
@@ -241,7 +253,9 @@ func TestArgon2Configuration_Validate(t *testing.T) {
KeyLength: 1,
},
},
want: ErrInvalidConfiguration,
wantErr: true,
wantErrIs: errors.PasswordInvalidConfiguration,
wantErrMsg: "password.(Argon2Configuration).validate: missing salt length: password violation: error #202",
},
{
name: "invalid-key-length",
@@ -254,7 +268,9 @@ func TestArgon2Configuration_Validate(t *testing.T) {
KeyLength: 0,
},
},
want: ErrInvalidConfiguration,
wantErr: true,
wantErrIs: errors.PasswordInvalidConfiguration,
wantErrMsg: "password.(Argon2Configuration).validate: missing key length: password violation: error #202",
},
}
for _, tt := range tests {
@@ -262,12 +278,13 @@ func TestArgon2Configuration_Validate(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
got := tt.in.validate()
if tt.want == nil {
assert.NoErrorf(got, "valid argon2 configuration: %+v", tt.in)
if tt.wantErr {
require.Error(got)
assert.Truef(errors.Match(errors.T(tt.wantErrIs), got), "want err code: %q got err: %q", tt.wantErrIs, got)
assert.Equal(tt.wantErrMsg, got.Error())
return
}
require.Error(got)
assert.Truef(errors.Is(got, tt.want), "want err: %q got: %q", tt.want, got)
assert.NoErrorf(got, "valid argon2 configuration: %+v", tt.in)
})
}
}
-22
View File
@@ -1,22 +0,0 @@
package password
import "github.com/hashicorp/boundary/internal/errors"
// TODO: remove these errors once all code has been refactored to creating inline domain errors
var (
// ErrTooShort results from attempting to set a password which is to
// short.
ErrTooShort = errors.E(errors.WithCode(errors.PasswordTooShort))
// ErrUnsupportedConfiguration results from attempting to perform an
// operation that sets a password configuration to an unsupported type.
ErrUnsupportedConfiguration = errors.E(errors.WithCode(errors.PasswordUnsupportedConfiguration))
// ErrInvalidConfiguration results from attempting to perform an
// operation that sets a password configuration with invalid settings.
ErrInvalidConfiguration = errors.E(errors.WithCode(errors.PasswordInvalidConfiguration))
// ErrPasswordsEqual is returned from ChangePassword when the old and
// new passwords are equal.
ErrPasswordsEqual = errors.E(errors.WithCode(errors.PasswordsEqual))
)
+2 -2
View File
@@ -17,7 +17,7 @@ func newArgon2ConfigurationId() (string, error) {
if err != nil {
return "", errors.Wrap(err, op)
}
return id, err
return id, nil
}
func newArgon2CredentialId() (string, error) {
@@ -26,5 +26,5 @@ func newArgon2CredentialId() (string, error) {
if err != nil {
return "", errors.Wrap(err, op)
}
return id, err
return id, nil
}
+2 -2
View File
@@ -17,7 +17,7 @@ func newAuthMethodId() (string, error) {
if err != nil {
return "", errors.Wrap(err, op)
}
return id, err
return id, nil
}
func newAccountId() (string, error) {
@@ -26,5 +26,5 @@ func newAccountId() (string, error) {
if err != nil {
return "", errors.Wrap(err, op)
}
return id, err
return id, nil
}
+15 -9
View File
@@ -89,16 +89,16 @@ func (r *Repository) CreateAccount(ctx context.Context, scopeId string, a *Accou
func(_ db.Reader, w db.Writer) error {
newAccount = a.clone()
if err := w.Create(ctx, newAccount, db.WithOplog(oplogWrapper, a.oplog(oplog.OpType_OP_TYPE_CREATE))); err != nil {
return err
return errors.Wrap(err, op)
}
if cred != nil {
newCred = cred.clone()
if err := newCred.encrypt(ctx, databaseWrapper); err != nil {
return err
return errors.Wrap(err, op)
}
if err := w.Create(ctx, newCred, db.WithOplog(oplogWrapper, cred.oplog(oplog.OpType_OP_TYPE_CREATE))); err != nil {
return err
return errors.Wrap(err, op)
}
}
return nil
@@ -180,10 +180,13 @@ func (r *Repository) DeleteAccount(ctx context.Context, scopeId, withPublicId st
metadata := ac.oplog(oplog.OpType_OP_TYPE_DELETE)
dAc := ac.clone()
rowsDeleted, err = w.Delete(ctx, dAc, db.WithOplog(oplogWrapper, metadata))
if err == nil && rowsDeleted > 1 {
return errors.ErrMultipleRecords
if err != nil {
return errors.Wrap(err, op)
}
return err
if rowsDeleted > 1 {
return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been deleted")
}
return nil
},
)
@@ -291,10 +294,13 @@ func (r *Repository) UpdateAccount(ctx context.Context, scopeId string, a *Accou
returnedAccount = a.clone()
var err error
rowsUpdated, err = w.Update(ctx, returnedAccount, dbMask, nullFields, db.WithOplog(oplogWrapper, metadata), db.WithVersion(&version))
if err == nil && rowsUpdated > 1 {
return errors.ErrMultipleRecords
if err != nil {
return errors.Wrap(err, op)
}
return err
if rowsUpdated > 1 {
return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been updated")
}
return nil
},
)
@@ -695,7 +695,7 @@ func TestRepository_UpdateAccount(t *testing.T) {
chgFn: combine(nonExistentPublicId(), changeName("test-update-name-repo")),
masks: []string{"Name"},
wantIsErr: errors.RecordNotFound,
wantErrMsg: "password.(Repository).UpdateAccount: abcd_OOOOOOOOOO: db.DoTx: db.Update: db.lookupAfterWrite: db.LookupById: record not found, search issue: error #1100",
wantErrMsg: "password.(Repository).UpdateAccount: abcd_OOOOOOOOOO: db.DoTx: password.(Repository).UpdateAccount: db.Update: db.lookupAfterWrite: db.LookupById: record not found, search issue: error #1100",
},
{
name: "empty-field-mask",
+19 -10
View File
@@ -79,10 +79,13 @@ func (r *Repository) CreateAuthMethod(ctx context.Context, m *AuthMethod, opt ..
func(_ db.Reader, w db.Writer) error {
newArgon2Conf = c.clone()
if err := w.Create(ctx, newArgon2Conf, db.WithOplog(oplogWrapper, c.oplog(oplog.OpType_OP_TYPE_CREATE))); err != nil {
return err
return errors.Wrap(err, op, errors.WithMsg("unable to create argon conf"))
}
newAuthMethod = m.clone()
return w.Create(ctx, newAuthMethod, db.WithOplog(oplogWrapper, m.oplog(oplog.OpType_OP_TYPE_CREATE)))
if err := w.Create(ctx, newAuthMethod, db.WithOplog(oplogWrapper, m.oplog(oplog.OpType_OP_TYPE_CREATE))); err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to create auth method"))
}
return nil
},
)
@@ -97,7 +100,7 @@ func (r *Repository) CreateAuthMethod(ctx context.Context, m *AuthMethod, opt ..
// LookupAuthMethod will look up an auth method in the repository. If the auth method is not
// found, it will return nil, nil. All options are ignored.
func (r *Repository) LookupAuthMethod(ctx context.Context, publicId string, opt ...Option) (*AuthMethod, error) {
func (r *Repository) LookupAuthMethod(ctx context.Context, publicId string, _ ...Option) (*AuthMethod, error) {
const op = "password.(Repository).LookupAuthMethod"
if publicId == "" {
return nil, errors.New(errors.InvalidPublicId, op, "missing public id")
@@ -158,10 +161,13 @@ func (r *Repository) DeleteAuthMethod(ctx context.Context, scopeId, publicId str
metadata := am.oplog(oplog.OpType_OP_TYPE_DELETE)
dAc := am.clone()
rowsDeleted, err = w.Delete(ctx, dAc, db.WithOplog(oplogWrapper, metadata))
if err == nil && rowsDeleted > 1 {
return errors.ErrMultipleRecords
if err != nil {
return errors.Wrap(err, op)
}
return err
if rowsDeleted > 1 {
return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been deleted")
}
return nil
},
)
@@ -245,10 +251,13 @@ func (r *Repository) UpdateAuthMethod(ctx context.Context, authMethod *AuthMetho
nullFields,
dbOpts...,
)
if err == nil && rowsUpdated > 1 {
return errors.ErrMultipleRecords
if err != nil {
return errors.Wrap(err, op)
}
return err
if rowsUpdated > 1 {
return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been updated")
}
return nil
},
)
if err != nil {
@@ -257,5 +266,5 @@ func (r *Repository) UpdateAuthMethod(ctx context.Context, authMethod *AuthMetho
}
return nil, db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg(authMethod.PublicId))
}
return upAuthMethod, rowsUpdated, err
return upAuthMethod, rowsUpdated, nil
}
@@ -120,7 +120,7 @@ func TestRepository_CreateAuthMethod(t *testing.T) {
WithConfiguration(&Argon2Configuration{}),
},
wantIsErr: errors.PasswordInvalidConfiguration,
wantErrMsg: "password.(Repository).CreateAuthMethod: invalid parameters in password configuration, password violation: error #202",
wantErrMsg: "password.(Repository).CreateAuthMethod: password.(Argon2Configuration).validate: missing embedded config: password violation: error #202",
},
{
name: "invalid-with-config-unknown-config-type",
@@ -71,7 +71,7 @@ func (r *Repository) setArgon2Conf(ctx context.Context, scopeId string, c *Argon
id, err := newArgon2ConfigurationId()
if err != nil {
return nil, err
return nil, errors.Wrap(err, op)
}
c.PrivateId = id
@@ -93,24 +93,27 @@ func (r *Repository) setArgon2Conf(ctx context.Context, scopeId string, c *Argon
where, args := c.whereDup()
if err := rr.LookupWhere(ctx, newArgon2Conf, where, args...); err != nil {
if !errors.IsNotFoundError(err) {
return err
return errors.Wrap(err, op)
}
newArgon2Conf = c.clone()
if err := w.Create(ctx, newArgon2Conf, db.WithOplog(oplogWrapper, c.oplog(oplog.OpType_OP_TYPE_CREATE))); err != nil {
return err
return errors.Wrap(err, op)
}
}
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 errors.ErrMultipleRecords
if err != nil {
return errors.Wrap(err, op)
}
return err
if rowsUpdated > 1 {
return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been updated")
}
return nil
},
)
if err != nil {
return nil, err
return nil, errors.Wrap(err, op)
}
return newArgon2Conf, nil
}
@@ -128,9 +131,10 @@ func (c *currentConfig) TableName() string {
}
func (r *Repository) currentConfig(ctx context.Context, authMethodId string) (*currentConfig, error) {
const op = "password.(Repository).currentConfig"
var cc currentConfig
if err := r.reader.LookupWhere(ctx, &cc, "password_method_id = ?", authMethodId); err != nil {
return nil, err
return nil, errors.Wrap(err, op)
}
return &cc, nil
}
@@ -141,13 +145,13 @@ func (r *Repository) currentConfigForAccount(ctx context.Context, accountId stri
rows, err := r.reader.Query(ctx, currentConfigForAccountQuery, []interface{}{accountId})
if err != nil {
return nil, err
return nil, errors.Wrap(err, op)
}
defer rows.Close()
for rows.Next() {
var conf currentConfig
if err := r.reader.ScanRows(rows, &conf); err != nil {
return nil, err
return nil, errors.Wrap(err, op)
}
confs = append(confs, conf)
}
+22 -16
View File
@@ -86,10 +86,13 @@ func (r *Repository) Authenticate(ctx context.Context, scopeId, authMethodId, lo
_, err = r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{},
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 errors.ErrMultipleRecords
if err != nil {
return errors.Wrap(err, op)
}
return err
if rowsUpdated > 1 {
return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been updated")
}
return nil
},
)
if err != nil {
@@ -105,7 +108,7 @@ func (r *Repository) Authenticate(ctx context.Context, scopeId, authMethodId, lo
//
// Returns nil, db.ErrorRecordNotFound if the account doesn't exist.
// Returns nil, nil if old does not match the stored password for accountId.
// Returns nil, ErrPasswordsEqual if old and new are equal.
// Returns nil, error with code PasswordsEqual if old and new are equal.
func (r *Repository) ChangePassword(ctx context.Context, scopeId, accountId, old, new string, version uint32) (*Account, error) {
const op = "password.(Repository).ChangePassword"
if accountId == "" {
@@ -185,13 +188,16 @@ 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 errors.ErrMultipleRecords
}
if err != nil {
return err
return errors.Wrap(err, op)
}
return w.Create(ctx, newCred, db.WithOplog(oplogWrapper, newCred.oplog(oplog.OpType_OP_TYPE_CREATE)))
if rowsDeleted > 1 {
return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been deleted")
}
if err = w.Create(ctx, newCred, db.WithOplog(oplogWrapper, newCred.oplog(oplog.OpType_OP_TYPE_CREATE))); err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to create new credential"))
}
return nil
},
)
if err != nil {
@@ -209,13 +215,13 @@ func (r *Repository) authenticate(ctx context.Context, scopeId, authMethodId, lo
rows, err := r.reader.Query(ctx, authenticateQuery, []interface{}{authMethodId, loginName})
if err != nil {
return nil, err
return nil, errors.Wrap(err, op)
}
defer rows.Close()
for rows.Next() {
var aa authAccount
if err := r.reader.ScanRows(rows, &aa); err != nil {
return nil, err
return nil, errors.Wrap(err, op)
}
accts = append(accts, aa)
}
@@ -311,17 +317,17 @@ 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.IsNotFoundError(err) {
return err
return errors.Wrap(err, op)
}
}
if oldCred.PrivateId != "" {
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 errors.ErrMultipleRecords
}
if err != nil {
return err
return errors.Wrap(err, op)
}
if rowsDeleted > 1 {
return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been deleted")
}
}
if newCred != nil {
+16 -10
View File
@@ -89,7 +89,7 @@ func (r *Repository) CreateAuthToken(ctx context.Context, withIamUser *iam.User,
// different time resolutions easier.
expiration, err := ptypes.TimestampProto(time.Now().Add(r.timeToLiveDuration).Truncate(time.Second))
if err != nil {
return nil, err
return nil, errors.Wrap(err, op, errors.WithCode(errors.InvalidTimeStamp))
}
at.ExpirationTime = &timestamp.Timestamp{Timestamp: expiration}
@@ -114,11 +114,11 @@ func (r *Repository) CreateAuthToken(ctx context.Context, withIamUser *iam.User,
newAuthToken = at.clone()
if err := newAuthToken.encrypt(ctx, databaseWrapper); err != nil {
return err
return errors.Wrap(err, op)
}
// tokens are not replicated, so they don't need oplog entries.
if err := w.Create(ctx, newAuthToken); err != nil {
return err
return errors.Wrap(err, op)
}
newAuthToken.CtToken = nil
@@ -227,7 +227,7 @@ func (r *Repository) ValidateToken(ctx context.Context, id, token string, opt ..
return nil
})
if err != nil {
return nil, err
return nil, errors.Wrap(err, op)
}
return nil, nil
}
@@ -257,10 +257,13 @@ func (r *Repository) ValidateToken(ctx context.Context, id, token string, opt ..
nil,
[]string{"ApproximateLastAccessTime"},
)
if err == nil && rowsUpdated > 1 {
return errors.ErrMultipleRecords
if err != nil {
return errors.Wrap(err, op)
}
return err
if rowsUpdated > 1 {
return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been updated")
}
return nil
},
)
}
@@ -324,10 +327,13 @@ func (r *Repository) DeleteAuthToken(ctx context.Context, id string, opt ...Opti
deleteAT := at.clone()
// tokens are not replicated, so they don't need oplog entries.
rowsDeleted, err = w.Delete(ctx, deleteAT)
if err == nil && rowsDeleted > 1 {
return errors.ErrMultipleRecords
if err != nil {
return errors.Wrap(err, op)
}
return err
if rowsDeleted > 1 {
return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been deleted")
}
return nil
},
)
+3 -3
View File
@@ -130,13 +130,13 @@ func Convert(e error) *Err {
if pqError.Code.Class() == "23" { // class of integrity constraint violations
switch pqError.Code {
case "23505": // unique_violation
return E(WithMsg(pqError.Message), WithWrap(ErrNotUnique)).(*Err)
return E(WithMsg(pqError.Message), WithWrap(E(WithCode(NotUnique), WithMsg("unique constraint violation")))).(*Err)
case "23502": // not_null_violation
msg := fmt.Sprintf("%s must not be empty", pqError.Column)
return E(WithMsg(msg), WithWrap(ErrNotNull)).(*Err)
return E(WithMsg(msg), WithWrap(E(WithCode(NotNull), WithMsg("not null constraint violated")))).(*Err)
case "23514": // check_violation
msg := fmt.Sprintf("%s constraint failed", pqError.Constraint)
return E(WithMsg(msg), WithWrap(ErrCheckConstraint)).(*Err)
return E(WithMsg(msg), WithWrap(E(WithCode(CheckConstraint), WithMsg("check constraint violated")))).(*Err)
default:
return E(WithCode(NotSpecificIntegrity), WithMsg(pqError.Message)).(*Err)
}
+16 -14
View File
@@ -15,6 +15,7 @@ import (
func Test_ErrorE(t *testing.T) {
t.Parallel()
errRecordNotFound := errors.E(errors.WithCode(errors.RecordNotFound))
tests := []struct {
name string
opt []errors.Option
@@ -25,12 +26,12 @@ func Test_ErrorE(t *testing.T) {
opt: []errors.Option{
errors.WithCode(errors.InvalidParameter),
errors.WithOp("alice.Bob"),
errors.WithWrap(errors.ErrRecordNotFound),
errors.WithWrap(errRecordNotFound),
errors.WithMsg("test msg"),
},
want: &errors.Err{
Op: "alice.Bob",
Wrapped: errors.ErrRecordNotFound,
Wrapped: errRecordNotFound,
Msg: "test msg",
Code: errors.InvalidParameter,
},
@@ -54,22 +55,22 @@ func Test_ErrorE(t *testing.T) {
{
name: "uses-wrapped-code",
opt: []errors.Option{
errors.WithWrap(errors.ErrRecordNotFound),
errors.WithWrap(errRecordNotFound),
},
want: &errors.Err{
Code: errors.RecordNotFound,
Wrapped: errors.ErrRecordNotFound,
Wrapped: errRecordNotFound,
},
},
{
name: "conflicting-withCode-withWrap",
opt: []errors.Option{
errors.WithCode(errors.InvalidFieldMask),
errors.WithWrap(errors.ErrRecordNotFound),
errors.WithWrap(errRecordNotFound),
},
want: &errors.Err{
Code: errors.InvalidFieldMask,
Wrapped: errors.ErrRecordNotFound,
Wrapped: errRecordNotFound,
},
},
}
@@ -99,11 +100,11 @@ func Test_NewError(t *testing.T) {
op: "alice.Bob",
msg: "test msg",
opt: []errors.Option{
errors.WithWrap(errors.ErrRecordNotFound),
errors.WithWrap(errors.E(errors.WithCode(errors.RecordNotFound))),
},
want: &errors.Err{
Op: "alice.Bob",
Wrapped: errors.ErrRecordNotFound,
Wrapped: errors.E(errors.WithCode(errors.RecordNotFound)),
Msg: "test msg",
Code: errors.InvalidParameter,
},
@@ -338,6 +339,7 @@ func TestError_Error(t *testing.T) {
func TestError_Unwrap(t *testing.T) {
t.Parallel()
testErr := errors.E(errors.WithMsg("test error"))
errInvalidParameter := errors.E(errors.WithCode(errors.InvalidParameter), errors.WithMsg("test error"))
tests := []struct {
name string
@@ -347,9 +349,9 @@ func TestError_Unwrap(t *testing.T) {
}{
{
name: "ErrInvalidParameter",
err: errors.E(errors.WithWrap(errors.ErrInvalidParameter)),
want: errors.ErrInvalidParameter,
wantIsErr: errors.ErrInvalidParameter,
err: errors.E(errors.WithWrap(errInvalidParameter)),
want: errInvalidParameter,
wantIsErr: errInvalidParameter,
},
{
name: "testErr",
@@ -450,7 +452,7 @@ func TestConvertError(t *testing.T) {
e := errors.Convert(err)
require.NotNil(e)
assert.True(errors.Is(e, errors.ErrNotUnique))
assert.True(errors.Match(errors.T(errors.NotUnique), e))
assert.Equal("db.Exec: duplicate key value violates unique constraint \"test_table_name_key\": unique constraint violation: integrity violation: error #1002", e.Error())
})
t.Run("ErrCodeNotNull", func(t *testing.T) {
@@ -462,7 +464,7 @@ func TestConvertError(t *testing.T) {
e := errors.Convert(err)
require.NotNil(e)
assert.True(errors.Is(e, errors.ErrNotNull))
assert.True(errors.Match(errors.T(errors.NotNull), e))
assert.Equal("db.Exec: description must not be empty: not null constraint violated: integrity violation: error #1001", e.Error())
})
t.Run("ErrCodeCheckConstraint", func(t *testing.T) {
@@ -474,7 +476,7 @@ func TestConvertError(t *testing.T) {
e := errors.Convert(err)
require.NotNil(e)
assert.True(errors.Is(e, errors.ErrCheckConstraint))
assert.True(errors.Match(errors.T(errors.CheckConstraint), err))
assert.Equal("db.Exec: test_table_five_check constraint failed: check constraint violated: integrity violation: error #1000", e.Error())
})
t.Run("MissingTable", func(t *testing.T) {
+9 -14
View File
@@ -39,13 +39,13 @@ func TestError_IsUnique(t *testing.T) {
want: true,
},
{
name: "ErrCodeUnique",
in: errors.ErrNotUnique,
name: "CodeUnique",
in: errors.E(errors.WithCode(errors.NotUnique)),
want: true,
},
{
name: "wrapped-pq-is-unique",
in: errors.E(errors.WithCode(errors.NotUnique),
in: errors.E(
errors.WithWrap(&pq.Error{
Code: pq.ErrorCode("23505"),
}),
@@ -53,8 +53,8 @@ func TestError_IsUnique(t *testing.T) {
want: true,
},
{
name: "ErrRecordNotFound",
in: errors.ErrRecordNotFound,
name: "RecordNotFound",
in: errors.E(errors.WithCode(errors.RecordNotFound)),
want: false,
},
{
@@ -115,8 +115,8 @@ func TestError_IsCheckConstraint(t *testing.T) {
want: true,
},
{
name: "ErrRecordNotFound",
in: errors.ErrRecordNotFound,
name: "RecordNotFound",
in: errors.E(errors.WithCode(errors.RecordNotFound)),
want: false,
},
{
@@ -184,8 +184,8 @@ func TestError_IsNotNullError(t *testing.T) {
want: true,
},
{
name: "ErrRecordNotFound",
in: errors.ErrRecordNotFound,
name: "RecordNotFound",
in: errors.E(errors.WithCode(errors.RecordNotFound)),
want: false,
},
{
@@ -273,11 +273,6 @@ func TestError_IsNotFoundError(t *testing.T) {
in: errors.E(errors.WithCode(errors.RecordNotFound)),
want: true,
},
{
name: "sentinel-not-found",
in: errors.ErrRecordNotFound,
want: true,
},
{
name: "std-err",
in: fmt.Errorf("std error"),
+15 -12
View File
@@ -140,6 +140,9 @@ func TestTemplate_Error(t *testing.T) {
func TestMatch(t *testing.T) {
t.Parallel()
stdErr := stderrors.New("test error")
errInvalidFieldMask := E(WithCode(InvalidFieldMask), WithMsg("test invalid field mask error"))
errNotUnique := E(WithCode(NotUnique), WithMsg("test not unique error"))
tests := []struct {
name string
template *Template
@@ -165,7 +168,7 @@ func TestMatch(t *testing.T) {
WithCode(NotUnique),
WithMsg("this thing must be unique"),
WithOp("alice.Bob"),
WithWrap(ErrInvalidFieldMask),
WithWrap(errInvalidFieldMask),
),
want: true,
},
@@ -176,7 +179,7 @@ func TestMatch(t *testing.T) {
WithCode(RecordNotFound),
WithMsg("this thing is missing"),
WithOp("alice.Bob"),
WithWrap(ErrInvalidFieldMask),
WithWrap(errInvalidFieldMask),
),
want: false,
},
@@ -187,7 +190,7 @@ func TestMatch(t *testing.T) {
WithCode(NotUnique),
WithMsg("this thing must be unique"),
WithOp("alice.Bob"),
WithWrap(ErrInvalidFieldMask),
WithWrap(errInvalidFieldMask),
),
want: true,
},
@@ -198,7 +201,7 @@ func TestMatch(t *testing.T) {
WithCode(RecordNotFound),
WithMsg("this thing is missing"),
WithOp("alice.Bob"),
WithWrap(ErrInvalidFieldMask),
WithWrap(errInvalidFieldMask),
),
want: false,
},
@@ -209,7 +212,7 @@ func TestMatch(t *testing.T) {
WithCode(NotUnique),
WithMsg("this thing must be unique"),
WithOp("alice.Bob"),
WithWrap(ErrInvalidFieldMask),
WithWrap(errInvalidFieldMask),
),
want: true,
},
@@ -220,7 +223,7 @@ func TestMatch(t *testing.T) {
WithCode(RecordNotFound),
WithMsg("this thing is missing"),
WithOp("alice.Bob"),
WithWrap(ErrInvalidFieldMask),
WithWrap(errInvalidFieldMask),
),
want: false,
},
@@ -230,36 +233,36 @@ func TestMatch(t *testing.T) {
"this thing must be unique",
Integrity,
InvalidParameter,
ErrInvalidFieldMask,
errInvalidFieldMask,
Op("alice.Bob"),
),
err: E(
WithCode(InvalidParameter),
WithMsg("this thing must be unique"),
WithOp("alice.Bob"),
WithWrap(ErrInvalidFieldMask),
WithWrap(errInvalidFieldMask),
),
want: true,
},
{
name: "match on Wrapped only",
template: T(ErrInvalidFieldMask),
template: T(errInvalidFieldMask),
err: E(
WithCode(NotUnique),
WithMsg("this thing must be unique"),
WithOp("alice.Bob"),
WithWrap(ErrInvalidFieldMask),
WithWrap(errInvalidFieldMask),
),
want: true,
},
{
name: "no match on Wrapped only",
template: T(ErrNotUnique),
template: T(errNotUnique),
err: E(
WithCode(RecordNotFound),
WithMsg("this thing is missing"),
WithOp("alice.Bob"),
WithWrap(ErrInvalidFieldMask),
WithWrap(errInvalidFieldMask),
),
want: false,
},
+4 -2
View File
@@ -30,9 +30,11 @@ func Test_getOpts(t *testing.T) {
testOpts.withErrWrapped = nil
assert.Equal(opts, testOpts)
testErr := E(WithCode(InvalidParameter), WithMsg("test error"))
// try setting it
opts = GetOpts(WithWrap(ErrInvalidParameter))
testOpts.withErrWrapped = ErrInvalidParameter
opts = GetOpts(WithWrap(testErr))
testOpts.withErrWrapped = testErr
assert.Equal(opts, testOpts)
})
t.Run("WithOp", func(t *testing.T) {
-44
View File
@@ -1,44 +0,0 @@
package errors
// Errors returned from this package may be tested against these errors
// with errors.Is. Creating new Sentinel type errors like these should be
// deprecated in favor of the new Err type that includes unique Codes and a
// Matching function.
var (
// ErrInvalidPublicId indicates an invalid PublicId.
ErrInvalidPublicId = E(WithCode(InvalidParameter), WithMsg("invalid publicId"))
// ErrInvalidParameter is returned by create and update methods if
// an attribute on a struct contains illegal or invalid values.
ErrInvalidParameter = E(WithCode(InvalidParameter), WithMsg("invalid parameter"))
// ErrInvalidFieldMask is returned by update methods if the field mask
// contains unknown fields or fields that cannot be updated.
ErrInvalidFieldMask = E(WithCode(InvalidFieldMask), WithMsg("invalid field mask"))
// ErrEmptyFieldMask is returned by update methods if the field mask is
// empty.
ErrEmptyFieldMask = E(WithCode(EmptyFieldMask), WithMsg("empty field mask"))
// ErrNotUnique is returned by create and update methods when a write
// to the repository resulted in a unique constraint violation.
ErrNotUnique = E(WithCode(NotUnique), WithMsg("unique constraint violation"))
// ErrNotNull is returned by methods when a write to the repository resulted
// in a check constraint violation
ErrCheckConstraint = E(WithCode(CheckConstraint), WithMsg("check constraint violated"))
// ErrNotNull is returned by methods when a write to the repository resulted
// in a not null constraint violation
ErrNotNull = E(WithCode(NotNull), WithMsg("not null constraint violated"))
// 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 = E(WithCode(RecordNotFound), WithMsg("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 = E(WithCode(MultipleRecords), WithMsg("multiple records"))
)
@@ -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, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err)
assert.Truef(errors.Match(errors.T(errors.NotUnique), err), "want err code: %v got err: %v", errors.NotUnique, err)
assert.Nil(got2)
})
@@ -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, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err)
assert.Truef(errors.Match(errors.T(errors.NotUnique), err), "want err code: %v got err: %v", errors.NotUnique, err)
assert.Nil(got2)
assert.Equal(db.NoRowsAffected, gotCount2, "row count")
})
@@ -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, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err)
assert.Truef(errors.Match(errors.T(errors.NotUnique), err), "want err code: %v got err: %v", errors.NotUnique, err)
assert.Nil(got2)
})
@@ -540,7 +540,7 @@ 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, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err)
assert.Truef(errors.Match(errors.T(errors.NotUnique), err), "want err code: %v got err: %v", errors.NotUnique, 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))
+2 -2
View File
@@ -205,7 +205,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, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err)
assert.Truef(errors.Match(errors.T(errors.NotUnique), err), "want err code: %v got err: %v", errors.NotUnique, err)
assert.Nil(got2)
})
@@ -660,7 +660,7 @@ 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, errors.ErrNotUnique), "want err: %v got: %v", errors.ErrNotUnique, err)
assert.Truef(errors.Match(errors.T(errors.NotUnique), err), "want err code: %v got err: %v", errors.NotUnique, 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))
@@ -294,7 +294,7 @@ func (s Service) updateInRepo(ctx context.Context, scopeId, authMethId, id strin
out, rowsUpdated, err := repo.UpdateAccount(ctx, scopeId, u, version, dbMask)
if err != nil {
switch {
case errors.Is(err, password.ErrTooShort):
case errors.Match(errors.T(errors.PasswordTooShort), err):
return nil, handlers.InvalidArgumentErrorf("Error in provided request.",
map[string]string{"attributes.login_name": "Length too short."})
}
@@ -351,10 +351,10 @@ func (s Service) changePasswordInRepo(ctx context.Context, scopeId, id string, v
switch {
case errors.IsNotFoundError(err):
return nil, handlers.NotFoundErrorf("Account not found.")
case errors.Is(err, password.ErrTooShort):
case errors.Match(errors.T(errors.PasswordTooShort), err):
return nil, handlers.InvalidArgumentErrorf("Error in provided request.",
map[string]string{"new_password": "Password is too short."})
case errors.Is(err, password.ErrPasswordsEqual):
case errors.Match(errors.T(errors.PasswordsEqual), err):
return nil, handlers.InvalidArgumentErrorf("Error in provided request.",
map[string]string{"new_password": "New password equal to current password."})
}
@@ -376,7 +376,7 @@ func (s Service) setPasswordInRepo(ctx context.Context, scopeId, id string, vers
switch {
case errors.IsNotFoundError(err):
return nil, handlers.NotFoundErrorf("Account not found.")
case errors.Is(err, password.ErrTooShort):
case errors.Match(errors.T(errors.PasswordTooShort), err):
return nil, handlers.InvalidArgumentErrorf("Error in provided request.",
map[string]string{"password": "Password is too short."})
}
@@ -153,12 +153,11 @@ func backendErrorToApiError(inErr error) error {
Message: stErr.Message(),
},
}
case errors.Is(inErr, errors.ErrRecordNotFound), errors.Match(errors.T(errors.RecordNotFound), inErr):
case errors.Match(errors.T(errors.RecordNotFound), inErr):
return NotFoundErrorf(genericNotFoundMsg)
case errors.Is(inErr, errors.ErrInvalidFieldMask), errors.Is(inErr, errors.ErrEmptyFieldMask),
errors.Match(errors.T(errors.InvalidFieldMask), inErr), errors.Match(errors.T(errors.EmptyFieldMask), inErr):
case errors.Match(errors.T(errors.InvalidFieldMask), inErr), errors.Match(errors.T(errors.EmptyFieldMask), inErr):
return InvalidArgumentErrorf("Error in provided request", map[string]string{"update_mask": "Invalid update mask provided."})
case errors.IsUniqueError(inErr), errors.Is(inErr, errors.ErrNotUnique):
case errors.IsUniqueError(inErr):
return InvalidArgumentErrorf(genericUniquenessMsg, nil)
}
@@ -3,7 +3,6 @@ package handlers
import (
"context"
stderrors "errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
@@ -106,18 +105,7 @@ func TestApiErrorHandler(t *testing.T) {
},
},
{
name: "Db invalid public id error",
err: fmt.Errorf("test error: %w", errors.ErrInvalidPublicId),
expected: apiError{
status: http.StatusInternalServerError,
inner: &pb.Error{
Kind: "Internal",
Message: fmt.Sprintf("test error: %s", errors.ErrInvalidPublicId),
},
},
},
{
name: "Domain error Db invalid parameter",
name: "Domain error Db invalid public id",
err: errors.E(errors.WithCode(errors.InvalidPublicId)),
expected: apiError{
status: http.StatusInternalServerError,
@@ -127,17 +115,6 @@ func TestApiErrorHandler(t *testing.T) {
},
},
},
{
name: "Db invalid parameter",
err: fmt.Errorf("test error: %w", errors.ErrInvalidParameter),
expected: apiError{
status: http.StatusInternalServerError,
inner: &pb.Error{
Kind: "Internal",
Message: fmt.Sprintf("test error: %s", errors.ErrInvalidParameter),
},
},
},
{
name: "Domain error Db invalid parameter",
err: errors.E(errors.WithCode(errors.InvalidParameter)),
@@ -149,18 +126,6 @@ func TestApiErrorHandler(t *testing.T) {
},
},
},
{
name: "Db invalid field mask",
err: fmt.Errorf("test error: %w", errors.ErrInvalidFieldMask),
expected: apiError{
status: http.StatusBadRequest,
inner: &pb.Error{
Kind: "InvalidArgument",
Message: "Error in provided request",
Details: &pb.ErrorDetails{RequestFields: []*pb.FieldError{{Name: "update_mask", Description: "Invalid update mask provided."}}},
},
},
},
{
name: "Domain error Db invalid field mask",
err: errors.E(errors.WithCode(errors.InvalidFieldMask)),
@@ -173,18 +138,6 @@ func TestApiErrorHandler(t *testing.T) {
},
},
},
{
name: "Db empty field mask",
err: fmt.Errorf("test error: %w", errors.ErrEmptyFieldMask),
expected: apiError{
status: http.StatusBadRequest,
inner: &pb.Error{
Kind: "InvalidArgument",
Message: "Error in provided request",
Details: &pb.ErrorDetails{RequestFields: []*pb.FieldError{{Name: "update_mask", Description: "Invalid update mask provided."}}},
},
},
},
{
name: "Domain error Db empty field mask",
err: errors.E(errors.WithCode(errors.EmptyFieldMask)),
@@ -197,17 +150,6 @@ func TestApiErrorHandler(t *testing.T) {
},
},
},
{
name: "Db not unique",
err: fmt.Errorf("test error: %w", errors.ErrNotUnique),
expected: apiError{
status: http.StatusBadRequest,
inner: &pb.Error{
Kind: "InvalidArgument",
Message: genericUniquenessMsg,
},
},
},
{
name: "Domain error Db not unqiue",
err: errors.E(errors.WithCode(errors.NotUnique)),
@@ -219,17 +161,6 @@ func TestApiErrorHandler(t *testing.T) {
},
},
},
{
name: "Db record not found",
err: fmt.Errorf("test error: %w", errors.ErrRecordNotFound),
expected: apiError{
status: http.StatusNotFound,
inner: &pb.Error{
Kind: "NotFound",
Message: genericNotFoundMsg,
},
},
},
{
name: "Domain error Db record not found",
err: errors.E(errors.WithCode(errors.RecordNotFound)),
@@ -241,17 +172,6 @@ func TestApiErrorHandler(t *testing.T) {
},
},
},
{
name: "Db multiple records",
err: fmt.Errorf("test error: %w", errors.ErrMultipleRecords),
expected: apiError{
status: http.StatusInternalServerError,
inner: &pb.Error{
Kind: "Internal",
Message: fmt.Sprintf("test error: %s", errors.ErrMultipleRecords),
},
},
},
{
name: "Domain error Db multiple records",
err: errors.E(errors.WithCode(errors.MultipleRecords)),
-11
View File
@@ -1,11 +0,0 @@
package session
import "errors"
// Errors returned from this package may be tested against these errors
// with errors.Is.
var (
// ErrInvalidStateForOperation indicates the session's state does not allow the
// operation.
ErrInvalidStateForOperation = errors.New("state is invalid for operation")
)
+6 -6
View File
@@ -385,15 +385,15 @@ func (r *Repository) TerminateCompletedSessions(ctx context.Context) (int, error
// * number of connections already created is less than session.ConnectionLimit
// If authorization is success, it creates/stores a new connection in the repo
// and returns it, along with it's states. If the authorization fails, it
// an error of ErrInvalidStateForOperation.
// an error with Code InvalidSessionState.
func (r *Repository) AuthorizeConnection(ctx context.Context, sessionId string) (*Connection, []*ConnectionState, *ConnectionAuthzSummary, error) {
const op = "session.(Repository).AuthorizeConnection"
if sessionId == "" {
return nil, nil, nil, status.Errorf(codes.FailedPrecondition, "authorize connection: missing session id: %v", errors.ErrInvalidParameter)
return nil, nil, nil, errors.Wrap(status.Error(codes.FailedPrecondition, "missing session id"), op, errors.WithCode(errors.InvalidParameter))
}
connectionId, err := newConnectionId()
if err != nil {
return nil, nil, nil, status.Errorf(codes.Internal, "authorize connection: %v", err)
return nil, nil, nil, errors.Wrap(err, op)
}
connection := AllocConnection()
@@ -406,13 +406,13 @@ func (r *Repository) AuthorizeConnection(ctx context.Context, sessionId string)
func(reader db.Reader, w db.Writer) error {
rowsAffected, err := w.Exec(ctx, authorizeConnectionCte, []interface{}{sessionId, connectionId})
if err != nil {
return status.Errorf(codes.Internal, "unable to authorize connection %s: %v", sessionId, err)
return errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("unable to authorize connection %s", sessionId)))
}
if rowsAffected == 0 {
return status.Errorf(codes.PermissionDenied, "authorize connection: session %s is not authorized (not active, expired or connection limit reached): %v", sessionId, ErrInvalidStateForOperation)
return errors.Wrap(status.Errorf(codes.PermissionDenied, "session %s is not authorized (not active, expired or connection limit reached)", sessionId), op, errors.WithCode(errors.InvalidSessionState))
}
if err := reader.LookupById(ctx, &connection); err != nil {
return status.Errorf(codes.Internal, "authorize connection: failed for session %s: %v", sessionId, err)
return errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("failed for session %s", sessionId)))
}
connectionStates, err = fetchConnectionStates(ctx, reader, connectionId, db.WithOrder("start_time desc"))
if err != nil {