forked from mtusi2026/mtusi2026lab3
106 lines
2.1 KiB
Go
106 lines
2.1 KiB
Go
package security
|
|
|
|
import (
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestPasswordHashAndVerify(t *testing.T) {
|
|
password := "Correct-password-123"
|
|
|
|
encodedHash, err := HashPassword(password)
|
|
if err != nil {
|
|
t.Fatalf("HashPassword returned error: %v", err)
|
|
}
|
|
|
|
if strings.Contains(encodedHash, password) {
|
|
t.Fatal("encoded hash contains plaintext password")
|
|
}
|
|
|
|
matches, err := VerifyPassword(password, encodedHash)
|
|
if err != nil {
|
|
t.Fatalf("VerifyPassword returned error: %v", err)
|
|
}
|
|
if !matches {
|
|
t.Fatal("correct password did not match")
|
|
}
|
|
|
|
matches, err = VerifyPassword("Wrong-password-123", encodedHash)
|
|
if err != nil {
|
|
t.Fatalf("VerifyPassword returned error: %v", err)
|
|
}
|
|
if matches {
|
|
t.Fatal("wrong password matched")
|
|
}
|
|
}
|
|
|
|
func TestPasswordHashesUseDifferentSalts(t *testing.T) {
|
|
password := "Correct-password-123"
|
|
|
|
firstHash, err := HashPassword(password)
|
|
if err != nil {
|
|
t.Fatalf("first HashPassword returned error: %v", err)
|
|
}
|
|
|
|
secondHash, err := HashPassword(password)
|
|
if err != nil {
|
|
t.Fatalf("second HashPassword returned error: %v", err)
|
|
}
|
|
|
|
if firstHash == secondHash {
|
|
t.Fatal("equal passwords produced equal encoded hashes")
|
|
}
|
|
}
|
|
|
|
func TestPasswordValidation(t *testing.T) {
|
|
testCases := []struct {
|
|
name string
|
|
password string
|
|
wantErr bool
|
|
}{
|
|
{
|
|
name: "minimum length",
|
|
password: "123456789012",
|
|
wantErr: false,
|
|
},
|
|
{
|
|
name: "unicode",
|
|
password: "пароль-проверка-123",
|
|
wantErr: false,
|
|
},
|
|
{
|
|
name: "colon is allowed",
|
|
password: "password:with:colon",
|
|
wantErr: false,
|
|
},
|
|
{
|
|
name: "too short",
|
|
password: "short",
|
|
wantErr: true,
|
|
},
|
|
}
|
|
|
|
for _, testCase := range testCases {
|
|
t.Run(testCase.name, func(t *testing.T) {
|
|
err := ValidatePassword(testCase.password)
|
|
|
|
if testCase.wantErr && err == nil {
|
|
t.Fatal("expected validation error")
|
|
}
|
|
if !testCase.wantErr && err != nil {
|
|
t.Fatalf("unexpected validation error: %v", err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestMalformedPasswordHash(t *testing.T) {
|
|
_, err := VerifyPassword(
|
|
"Correct-password-123",
|
|
"not-an-argon2-hash",
|
|
)
|
|
if err == nil {
|
|
t.Fatal("expected malformed hash error")
|
|
}
|
|
}
|