Files
kopia/internal/user/hash_password_test.go
Julio López 9c5fc842a1 feat(cli): add server user set-password-hash command (#3974)
Objectives:
- Facilitate the generation of valid password hashes that can be used with
  the `server user --user-password` CLI command.
- Encapsulate implementation details of password hashing in
  the `user` package.

Adds a new `server user hash-password` CLI command to generate the
hash from a supplied password.

Modifies the `server user set/add --user-password-hash` CLI command
to accept the password hash generated using the `hash-password`
command.

Adds `GetNewProfile(ctx, rep, username)` helper to move implementation
details to the `user` package.

Includes CLI and unit tests.

Cleans up and removes unused functions.
2024-07-11 19:29:06 -07:00

86 lines
1.6 KiB
Go

package user
import (
"strconv"
"testing"
petname "github.com/dustinkirkland/golang-petname"
"github.com/stretchr/testify/require"
)
func TestHashPassword_encoding(t *testing.T) {
bogusPassword := petname.Generate(2, "+")
h, err := HashPassword(bogusPassword)
require.NoError(t, err)
require.NotEmpty(t, h)
// roundtrip
ph, err := decodeHashedPassword(h)
require.NoError(t, err)
require.NotEmpty(t, ph)
require.NotZero(t, ph.PasswordHashVersion)
require.NotEmpty(t, ph.PasswordHash)
p := Profile{
PasswordHashVersion: ph.PasswordHashVersion,
PasswordHash: ph.PasswordHash,
}
valid, err := p.IsValidPassword(bogusPassword)
require.NoError(t, err)
require.True(t, valid)
}
func TestPasswordHashValidate(t *testing.T) {
cases := []struct {
ph passwordHash
expectError bool
}{
{
expectError: true,
},
{
ph: passwordHash{
PasswordHashVersion: -3,
},
expectError: true,
},
{
ph: passwordHash{
PasswordHashVersion: defaultPasswordHashVersion,
// empty PasswordHash
},
expectError: true,
},
{
ph: passwordHash{
PasswordHashVersion: defaultPasswordHashVersion,
// PasswordHash with invalid length
PasswordHash: []byte{'z', 'a'},
},
expectError: true,
},
{
ph: passwordHash{
PasswordHashVersion: defaultPasswordHashVersion,
PasswordHash: make([]byte, passwordHashSaltLength+passwordHashLength),
},
expectError: false,
},
}
for i, tc := range cases {
t.Run("i_"+strconv.Itoa(i), func(t *testing.T) {
gotErr := tc.ph.validate()
if tc.expectError {
require.Error(t, gotErr)
} else {
require.NoError(t, gotErr)
}
})
}
}