Files
threshold/internal/auth/password/repository_password_test.go
T
edd323b73a Key Rotation/Destruction (#2477) (#2607)
* Key Rotation/Destruction (#2477)

* fix: Correct kms.CreateKeys comment

This method does not return anything.

* feat(kms): Add new ListKeys method

The new ListKeys method wraps the underlying KMS wrapper,
returning all the keys in the scope specified.

* feat(scopes): Add new scope actions for key management

Adds list-keys, rotate-keys and revoke-keys actions for scopes.

* feat(scopes): Add ListKeys API endpoint

This new endpoint lists all keys in a scope

* feat(api): Add ListKeys to Scopes client

This has to be a custom function because it is a custom action
and doesn't map well to any of the existing templates, or
generalises well in a way that would make it reasonable
to create a new template.

* feat(cli): Add new scopes list-keys command

* add RotateKeys function to the kms repository

* Add Rotate Keys Endpoint to Scopes Api (#2360)

* add rotate keys endpoint

* add tests for RotateKeys endpoint

* remove that one comment I forgot about

* addressing more PR comments

* Add Rotate Keys CLI Command (#2395)

* add cli command and client

* add bats tests

* fix some info text and pr comments

* write a new rotate keys description

* Add Missing DEK Foreign Keys (#2408)

* add missing fks

* mark key as nullable in gorm

* update tests to use a new wrapper with a real key_id

* fix formatting in test and add keys for auth_token test

* replace key values

* revert postgres_40_01_test.go

* style: reformat sql for readability

* refactor: change type of key_id columns to kms_private_id

* Store key_id and scope_id with oplog entries, re-type columns referencing data key version (#2431)

* fix(db): Correct types of data key version referencers

* fix(oplog): Fix missing error handling

* feat(oplog): Store key_id and scope_id with oplog entries

This migration truncates all existing oplog entries, as
migrating existing data would have been complex and
likely unnecessary.

* Update view references

* Always delete oplog entries when dropping keys

* Fix rebase issues

* Fix sql tests

* Add schema for new kms destruction jobs (#2479)

* feat: Add schema for new kms destruction jobs

The schema lets us manage destruction jobs per-table
while providing a guarantee that only one run is running
at a time.

* Apply suggestions from code review

Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>

* Fix table reference and tests

Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>

* update domain, api, and cli to all include key versions in outputs (#2472)

* update domain, api, and cli to all include key versions in outputs

* fix go sum

* add migration to fix immutable error

* fix final test issue as well as make gen issue

* rebase and fix

* address johan pr comments

* make gen, didn't realize comments were included

* update migrations based on new migration 55 file 03

* Move migrations to 56

* feat: Add key version rewrapping function registry (#2478)

The new RegisterTableRewrapFn can be used by a domain
to register a callback to use when rewrapping data in a
specific table name.

* feat(kms): Add scopeId to RewrapFn (#2539)

This makes it much easier for rewrap functions to look up
the correct wrapper and limit the number of rows searched.

* Update Root Cert Proto Definition (#2542)

* update root cert proto definition to properly identify public_key as the table primary key

* add the test fix as well

* Rewrap Functions for Encrypted Tables (#2532)

* add oidc rewrap

* add argon2 config rewrap

* add auth token rewrapping

* add worker auth cert rewrapping

* check the err

* add username password credential rewrapping

* add ssh private key credential rewrapping

* add vault client certificate rewrap function

* add host catalog secret rewrap function

* cleanup a little

* add host vault token rewrap function

* add session credential rewrap function

* add session rewrap function

* add worker auth rewrap function

* update test to include full assert gamut

* add session rewrap function TEST

* bring all tests up to current standards, make more readable, and include full assert gamut

* rework all rewrap functions to utilize scope id

* update comments, queries, sql refs, etc, in response to PR comments

* forgot a comment

* remove hmac updates and fix a couple comments again

* Rewrapping Registered Tables Test (#2555)

* add the registered table test as well as the two missing rewrap functions

* address pr comments, add db r/w conversions, cmp.diff, sql comment, remove (now) faulty immutable test

* Add ability to list key version destruction jobs, recurring jobs and destroying key versions (#2498)

* feat(kms): Add ability to list data key version destruction jobs

* feat(scopes): Add ListKeyVersionDestructionJobs

* feat(cli): Add list-key-version-destruction-jobs

* feat(kms): Add recurring job that performs table rewrapping

The new recurring job runs for each job table with a registered
rewrapping callback. It attempts to become the running run and
start its rewrapping, gracefully handling sudden interruptions
by resuming it's work if it finds evidence of sudden interruption.

* feat(kms): Add recurring job for destroying key versions

The new job monitors the database for data key version destruction
jobs that have finished rewrapping all its data, performing
the final data key version revocation.

* feat(kms): Add DestroyKeyVersion

DestroyKeyVersion immediately destroys a key version
if it is a root key version or a data key version
which encrypts no data. If the data key version
encrypts data which needs to be rewrapped, it
queues an asynchronous job to complete the rewrapping
operation.

* feat(scopes): Add DestroyKeyVersion API endpoint

* feat(cli): Add scopes destroy-key-version CLI command

* Ensure all secret updates include key ID (#2556)

* feat(all): Ensure all secret updates include key ID

When updating a secret, it is paramount that the key ID
is also updated, as it is the only means we have of ensuring
that we only destroy keys once there is no more data
associated with the key.

* Remove fix to session repository for now

This breaks the current private key derivation method

* add new encrypt/decrypt funcs and made necessary proto changes (#2557)

* add new encrypt/decrypt funcs and made necessary proto changes

* address all PR comments

* fix test panic

* add param checking to rewraps

* fix(schema): Correctly organize migrations again

* Review comments part 1

* Review comments part 2

* Review comments part 3

* Store cert private key, encrypt tofu token (#2583)

* fix(session): store cert private key, encrypt tofu token

Previously, we would derive a session certificate private key from
the session key used in each project, and not store the key. We
would also encrypt the tofu token with the database key but not
store a reference to this key in the database.

This change fixes this by replacing our key derivation with a key
generation step, and instead store the generated key, encrypted,
in the database. We also ensure that any new tofu tokens are
encrypted with the same key.

To handle existing sessions, we lazily rewrite the sessions whenever
a user lists them. There is a minor risk that a user could end up
destroying the database key that encrypts the tofu token before
that session has been rewrapped, but this is going to be rare and
temporary.

* feat(session): Allow the random source for secrets to be configured

* Review comments

* Minor fixes

* More minor fixes

* More small fixes

Co-authored-by: Danielle Miu <dani.miu@hashicorp.com>
Co-authored-by: Danielle <29378233+DanielleMiu@users.noreply.github.com>
Co-authored-by: Michael Gaffney <mike@gaffney.cc>
Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>

* fix(session): Unset session key ID when scope is deleted

Unsetting the key ID allows the session to live beyond the lifetime of
the scope, while allowing the scope to cascade delete its keys.

* fix(migrations): Rewrite migration 56 tests

These tests can no longer use the normal test helpers
as they try to use the new oplog table structure, so we
have to manually write all the interactions.

* fix(migrations): Rename migration 58 file name

This was the name used in the release branch, update
it to the new migration number.

* fix(e2e): Add some comments and debug to kms tests

* fix(session): Handle empty project and user IDs in read

When a project or user is deleted, the session is automatically
canceled and the respective field on the session is unset.
LookupSession did not handle this case gracefully, and would
error on decryption in this state. Skip decrypting sessions that
do not have either a user or project to avoid this error. The
decrypted values are not used for a canceled session.

* Fix worker test

* Increase test timeout

Co-authored-by: Danielle Miu <dani.miu@hashicorp.com>
Co-authored-by: Danielle <29378233+DanielleMiu@users.noreply.github.com>
Co-authored-by: Michael Gaffney <mike@gaffney.cc>
Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>
2022-11-16 18:17:28 -05:00

563 lines
18 KiB
Go

package password
import (
"context"
"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"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRepository_Authenticate(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
kms := kms.TestKms(t, conn, wrapper)
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
authMethods := TestAuthMethods(t, conn, o.GetPublicId(), 1)
authMethod := authMethods[0]
inAcct := &Account{
Account: &store.Account{
AuthMethodId: authMethod.PublicId,
LoginName: "kazmierczak",
},
}
passwd := "12345678"
repo, err := NewRepository(rw, rw, kms)
assert.NoError(t, err)
require.NotNil(t, repo)
outAcct, err := repo.CreateAccount(context.Background(), o.GetPublicId(), inAcct, WithPassword(passwd))
assert.NoError(t, err)
require.NotNil(t, outAcct)
type args struct {
authMethodId string
loginName string
password string
}
tests := []struct {
name string
args args
want *Account
wantIsErr errors.Code
wantErrMsg string
}{
{
name: "invalid-no-authMethodId",
args: args{
authMethodId: "",
loginName: inAcct.LoginName,
password: passwd,
},
wantIsErr: errors.InvalidParameter,
wantErrMsg: "password.(Repository).Authenticate: missing authMethodId: parameter violation: error #100",
},
{
name: "invalid-no-loginName",
args: args{
authMethodId: inAcct.AuthMethodId,
loginName: "",
password: passwd,
},
wantIsErr: errors.InvalidParameter,
wantErrMsg: "password.(Repository).Authenticate: missing loginName: parameter violation: error #100",
},
{
name: "invalid-no-password",
args: args{
authMethodId: inAcct.AuthMethodId,
loginName: inAcct.LoginName,
password: "",
},
wantIsErr: errors.InvalidParameter,
wantErrMsg: "password.(Repository).Authenticate: missing password: parameter violation: error #100",
},
{
name: "valid-authenticate",
args: args{
authMethodId: inAcct.AuthMethodId,
loginName: inAcct.LoginName,
password: passwd,
},
want: outAcct,
},
{
name: "wrong-password",
args: args{
authMethodId: inAcct.AuthMethodId,
loginName: inAcct.LoginName,
password: "foobar",
},
want: nil,
wantIsErr: errors.Unknown,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
authAcct, err := repo.Authenticate(context.Background(), o.GetPublicId(), tt.args.authMethodId, tt.args.loginName, tt.args.password)
if tt.wantIsErr != 0 {
assert.Truef(errors.Match(errors.T(tt.wantIsErr), err), "Unexpected error %s", err)
assert.Equal(tt.wantErrMsg, err.Error())
return
}
require.NoError(err)
if tt.want == nil {
assert.Nil(authAcct)
return
}
require.NotNil(authAcct, "returned account")
assert.NotEmpty(authAcct.CredentialId, "CredentialId")
assert.Equal(tt.args.authMethodId, authAcct.AuthMethodId, "authMethodId")
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.IsNotFoundError(err))
})
}
}
func TestRepository_AuthenticateRehash(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
assert, require := assert.New(t), require.New(t)
kmsCache := kms.TestKms(t, conn, wrapper)
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
authMethods := TestAuthMethods(t, conn, o.GetPublicId(), 1)
authMethod := authMethods[0]
authMethodId := authMethod.GetPublicId()
loginName := "kazmierczak"
passwd := "12345678"
ctx := context.Background()
repo, err := NewRepository(rw, rw, kmsCache)
assert.NoError(err)
require.NotNil(repo)
// Get the default (original) argon2 configuration
origConf, err := repo.GetConfiguration(ctx, authMethodId)
assert.NoError(err)
require.NotNil(origConf)
origArgonConf, ok := origConf.(*Argon2Configuration)
require.True(ok, "want *Argon2Configuration")
require.NotEmpty(origArgonConf.PrivateId, "original configuration PrivateId")
origConfId := origArgonConf.PrivateId
// Create an account with a password
inAcct := &Account{
Account: &store.Account{
AuthMethodId: authMethod.PublicId,
LoginName: loginName,
},
}
origAcct, err := repo.CreateAccount(ctx, o.GetPublicId(), inAcct, WithPassword(passwd))
require.NoError(err)
require.NotNil(origAcct)
assert.NotEmpty(origAcct.PublicId)
// Get the credential for the new account and verify the KDF used the
// original argon2 configuration
origCred := &Argon2Credential{Argon2Credential: &store.Argon2Credential{}}
require.NoError(rw.LookupWhere(ctx, origCred, "password_account_id = ?", []any{origAcct.PublicId}))
assert.Equal(origAcct.PublicId, origCred.PasswordAccountId)
assert.Equal(origConfId, origCred.PasswordConfId)
assert.Equal(origCred.CreateTime, origCred.UpdateTime, "create and update times are equal")
origCredId := origCred.PrivateId
// Authenticate and verify the credential ID
authAcct, err := repo.Authenticate(ctx, o.GetPublicId(), authMethodId, loginName, passwd)
require.NoError(err)
require.NotNil(authAcct, "auth account")
assert.Equal(origAcct.PublicId, authAcct.PublicId)
assert.Equal(origCredId, authAcct.CredentialId)
auth1CredId := authAcct.CredentialId
// Get the credential and verify the call to Authenticate did not
// change anything
auth1Cred := &Argon2Credential{
Argon2Credential: &store.Argon2Credential{
PrivateId: auth1CredId,
},
}
require.NoError(rw.LookupById(ctx, auth1Cred))
assert.Equal(authAcct.PublicId, auth1Cred.PasswordAccountId)
assert.Equal(origConfId, auth1Cred.PasswordConfId)
assert.Equal(origCred.PasswordConfId, auth1Cred.PasswordConfId, "same configuration ID")
assert.Equal(origCred.Salt, auth1Cred.Salt, "same salt")
assert.Equal(origCred.DerivedKey, auth1Cred.DerivedKey, "same derived key")
assert.Equal(origCred.UpdateTime, auth1Cred.UpdateTime, "same update time")
// Change the argon2 configuration
inArgonConf := origArgonConf.clone()
inArgonConf.Threads = origArgonConf.Threads + 1
upConf, err := repo.SetConfiguration(ctx, o.GetPublicId(), inArgonConf)
require.NoError(err)
require.NotNil(upConf)
assert.NotSame(inArgonConf, upConf)
upArgonConf, ok := upConf.(*Argon2Configuration)
require.True(ok, "want *Argon2Configuration")
assert.NotEqual(origConfId, upArgonConf.PrivateId)
// Change the key used to encrypt the password too, to test
// that it gets updated appropriately
err = kmsCache.RotateKeys(ctx, o.GetPublicId())
require.NoError(err)
// Authenticate and verify the credential ID has not changed
auth2Acct, err := repo.Authenticate(ctx, o.GetPublicId(), authMethodId, loginName, passwd)
require.NoError(err)
require.NotNil(auth2Acct, "auth2 account")
assert.Equal(origAcct.PublicId, auth2Acct.PublicId)
require.Equal(origCredId, auth2Acct.CredentialId)
auth2CredId := auth2Acct.CredentialId
// Get the credential and verify the call to Authenticate changed the
// appropriate fields
auth2Cred := &Argon2Credential{
Argon2Credential: &store.Argon2Credential{
PrivateId: auth2CredId,
},
}
require.NoError(rw.LookupById(ctx, auth2Cred))
// Verify fields that should not change
assert.Equal(auth2Acct.PublicId, auth2Cred.PasswordAccountId)
assert.Equal(origCred.PrivateId, auth2Cred.PrivateId, "the credential Id should not change")
assert.Equal(origCred.CreateTime, auth2Cred.CreateTime, "the create time should not change")
// Verify fields that should change
decryptWrapper, err := kmsCache.GetWrapper(ctx, o.GetPublicId(), kms.KeyPurposeDatabase, kms.WithKeyId(auth2Cred.GetKeyId()))
require.NoError(err)
require.NoError(auth2Cred.decrypt(ctx, decryptWrapper))
assert.NotEqual(origCred.UpdateTime, auth2Cred.UpdateTime, "the update time should be different")
assert.NotEqual(origCred.PasswordConfId, auth2Cred.PasswordConfId, "the configuration Id should be different")
assert.NotEqual(origCred.Salt, auth2Cred.Salt, "a new salt value should be generated")
assert.NotEqual(origCred.DerivedKey, auth2Cred.DerivedKey, "the derived key should be different")
assert.NotEqual(origCred.KeyId, auth2Cred.KeyId)
assert.NoError(db.TestVerifyOplog(t, rw, auth2Cred.PrivateId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)))
}
func TestRepository_ChangePassword(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
kms := kms.TestKms(t, conn, wrapper)
repo, err := NewRepository(rw, rw, kms)
require.NoError(t, err)
require.NotNil(t, repo)
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
authMethod := TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
inAcct := &Account{
Account: &store.Account{
LoginName: "kazmierczak",
AuthMethodId: authMethod.PublicId,
},
}
passwd := "12345678"
acct, err := repo.CreateAccount(context.Background(), o.GetPublicId(), inAcct, WithPassword(passwd))
require.NoError(t, err)
require.NotNil(t, acct)
type args struct {
acctId string
old, new string
}
tests := []struct {
name string
args args
wantAccount bool
wantIsErr errors.Code
wantErrMsg string
}{
{
name: "invalid-no-accountId",
args: args{
acctId: "",
old: passwd,
new: "12345678-changed",
},
wantIsErr: errors.InvalidParameter,
wantErrMsg: "password.(Repository).ChangePassword: missing account id: parameter violation: error #100",
},
{
name: "invalid-no-current-password",
args: args{
acctId: acct.PublicId,
old: "",
new: "12345678-changed",
},
wantIsErr: errors.InvalidParameter,
wantErrMsg: "password.(Repository).ChangePassword: missing old password: parameter violation: error #100",
},
{
name: "invalid-no-new-password",
args: args{
acctId: acct.PublicId,
old: passwd,
new: "",
},
wantIsErr: errors.InvalidParameter,
wantErrMsg: "password.(Repository).ChangePassword: missing new password: parameter violation: error #100",
},
{
name: "invalid-same-passwords",
args: args{
acctId: acct.PublicId,
old: passwd,
new: passwd,
},
wantIsErr: errors.PasswordsEqual,
wantErrMsg: "password.(Repository).ChangePassword: passwords must not equal: password violation: error #203",
},
{
name: "auth-failure-unknown-accountId",
args: args{
acctId: "not-an-account-Id",
old: passwd,
new: "12345678-changed",
},
wantAccount: false,
wantIsErr: errors.RecordNotFound,
wantErrMsg: "password.(Repository).ChangePassword: account not found: search issue: error #1100",
},
{
name: "auth-failure-wrong-current-password",
args: args{
acctId: acct.PublicId,
old: "wrong-password",
new: "12345678-changed",
},
wantAccount: false,
},
{
name: "password-too-short",
args: args{
acctId: acct.PublicId,
old: passwd,
new: "1",
},
wantIsErr: errors.PasswordTooShort,
wantErrMsg: "password.(Repository).ChangePassword: must be at least 8: password violation: error #200",
},
{
name: "valid",
args: args{
acctId: acct.PublicId,
old: passwd,
new: "12345678-changed",
},
wantAccount: true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
// Calls to Authenticate should always succeed in these tests
authFn := func(pwd string, name string) *Account {
acct, err := repo.Authenticate(context.Background(), o.GetPublicId(), inAcct.AuthMethodId, inAcct.LoginName, pwd)
require.NotNilf(acct, "%s: Authenticate should return an account", name)
require.NoErrorf(err, "%s: Authenticate should succeed", name)
return acct
}
// authenticate with original password
authAcct1 := authFn(passwd, "original account")
chgAuthAcct, err := repo.ChangePassword(context.Background(), o.GetPublicId(), tt.args.acctId, tt.args.old, tt.args.new, authAcct1.Version)
if tt.wantIsErr != 0 {
assert.Truef(errors.Match(errors.T(tt.wantIsErr), err), "Unexpected error %s", err)
assert.Equal(tt.wantErrMsg, err.Error())
assert.Nil(chgAuthAcct, "returned account")
authAcct2 := authFn(passwd, "error changing password: using old password")
assert.Equal(authAcct1.CredentialId, authAcct2.CredentialId, "CredentialId should not change")
return
}
assert.NoError(err)
if !tt.wantAccount {
assert.Nil(chgAuthAcct)
authAcct2 := authFn(passwd, "no account from changing password: using old password")
assert.Equal(authAcct1.CredentialId, authAcct2.CredentialId, "CredentialId should not change")
return
}
require.NotNil(chgAuthAcct, "returned account")
assert.NotEmpty(chgAuthAcct.CredentialId, "CredentialId")
assert.NotEqual(authAcct1.CredentialId, chgAuthAcct.CredentialId, "CredentialId should change")
assert.Equal(authAcct1.AuthMethodId, chgAuthAcct.AuthMethodId, "authMethodId")
assert.Equal(authAcct1.LoginName, chgAuthAcct.LoginName, "LoginName")
authAcct2 := authFn(tt.args.new, "successful change password: using new password")
assert.Equal(chgAuthAcct.CredentialId, authAcct2.CredentialId, "CredentialId should not change")
assert.NoError(db.TestVerifyOplog(t, rw, authAcct1.CredentialId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)))
assert.NoError(db.TestVerifyOplog(t, rw, authAcct2.CredentialId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)))
})
}
}
func TestRepository_SetPassword(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
kms := kms.TestKms(t, conn, wrapper)
repo, err := NewRepository(rw, rw, kms)
require.NoError(t, err)
require.NotNil(t, repo)
o, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper))
authMethod := TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
origPasswd := "12345678"
createAccount := func(un string) func(string) *Account {
return func(pw string) *Account {
inAcct := &Account{
Account: &store.Account{
AuthMethodId: authMethod.PublicId,
LoginName: un,
},
}
var opts []Option
if pw != "" {
opts = append(opts, WithPassword(origPasswd))
}
acct, err := repo.CreateAccount(context.Background(), o.GetPublicId(), inAcct, opts...)
require.NoError(t, err)
require.NotNil(t, acct)
return acct
}
}
wantAuthenticate := func(t *testing.T, ln, pw, msg string) string {
acct, err := repo.Authenticate(context.Background(), o.GetPublicId(), authMethod.PublicId, ln, pw)
assert.NoErrorf(t, err, "%s: authenticate should not return an error", msg)
if assert.NotNilf(t, acct, "%s: authenticate should succeed", msg) {
return acct.CredentialId
}
return ""
}
wantNoAuthenticate := func(t *testing.T, ln, pw, msg string) string {
acct, err := repo.Authenticate(context.Background(), o.GetPublicId(), authMethod.PublicId, ln, pw)
assert.NoErrorf(t, err, "%s: authenticate should not return an error", msg)
assert.Nilf(t, acct, "%s: authenticate should not succeed", msg)
return ""
}
tests := []struct {
name string
oldPw string
newPw string
createAcct func(string) *Account
}{
{
name: "valid-new-password-no-current-password",
createAcct: createAccount("validnewpwnoold"),
oldPw: "",
newPw: "abcdefghijk",
},
{
name: "valid-new-password-delete-current-password",
createAcct: createAccount("validnewpwyesold"),
oldPw: origPasswd,
newPw: "abcdefghijk",
},
{
name: "valid-delete-password-no-new-password",
createAcct: createAccount("nonewyesold"),
oldPw: origPasswd,
newPw: "",
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
acct := tt.createAcct(tt.oldPw)
nextAuth := wantNoAuthenticate
if tt.oldPw != "" {
nextAuth = wantAuthenticate
}
oldCredId := nextAuth(t, acct.LoginName, origPasswd, "after create account")
acct, err = repo.SetPassword(context.Background(), o.GetPublicId(), acct.PublicId, tt.newPw, acct.Version)
require.NoError(err)
if oldCredId != "" {
wantNoAuthenticate(t, acct.LoginName, origPasswd, "old password")
assert.NoError(db.TestVerifyOplog(t, rw, oldCredId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)))
}
if tt.newPw != "" {
newCredId := wantAuthenticate(t, acct.LoginName, tt.newPw, "new password")
assert.NotEqual(oldCredId, newCredId)
assert.NoError(db.TestVerifyOplog(t, rw, newCredId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)))
}
})
}
badInputAcct := createAccount("badinputusername")("")
badInputCases := []struct {
name string
accountId string
pw string
version uint32
wantIsErr errors.Code
wantErrMsg string
}{
{
name: "no id",
pw: "anylongpassword",
version: 1,
wantIsErr: errors.InvalidParameter,
wantErrMsg: "password.(Repository).SetPassword: missing accountId: parameter violation: error #100",
},
{
name: "short pw",
accountId: badInputAcct.PublicId,
pw: "c",
version: 1,
wantIsErr: errors.PasswordTooShort,
wantErrMsg: "password.(Repository).SetPassword: password must be at least 8: password violation: error #200",
},
{
name: "no version",
accountId: badInputAcct.PublicId,
pw: "anylongpassword",
wantIsErr: errors.InvalidParameter,
wantErrMsg: "password.(Repository).SetPassword: missing version: parameter violation: error #100",
},
}
for _, tt := range badInputCases {
t.Run(tt.name, func(t *testing.T) {
assert := assert.New(t)
acct, err := repo.SetPassword(context.Background(), o.GetPublicId(), tt.accountId, tt.pw, tt.version)
assert.Error(err)
assert.Truef(errors.Match(errors.T(tt.wantIsErr), err), "Unexpected error %s", err)
assert.Equal(tt.wantErrMsg, err.Error())
assert.Nil(acct)
})
}
}