package service import ( "strings" "testing" ) func TestHashAndVerifyPassword(t *testing.T) { hash, err := hashPassword("correct-horse-battery-staple") if err != nil { t.Fatalf("hashPassword: %v", err) } if !strings.HasPrefix(hash, "$argon2id$v=19$") { t.Errorf("hash %q lacks argon2id PHC prefix", hash) } ok, err := verifyPassword(hash, "correct-horse-battery-staple") if err != nil || !ok { t.Errorf("verify correct = (%v, %v), want (true, nil)", ok, err) } ok, err = verifyPassword(hash, "wrong-password") if err != nil || ok { t.Errorf("verify wrong = (%v, %v), want (false, nil)", ok, err) } } func TestHashPasswordIsSalted(t *testing.T) { // Two hashes of the same password must differ (random salt), yet both verify. h1, _ := hashPassword("same-password") h2, _ := hashPassword("same-password") if h1 == h2 { t.Error("two hashes of the same password are identical; salt not random") } for _, h := range []string{h1, h2} { if ok, err := verifyPassword(h, "same-password"); err != nil || !ok { t.Errorf("verify(%q) = (%v, %v), want (true, nil)", h, ok, err) } } } func TestVerifyPasswordRejectsMalformedHash(t *testing.T) { for _, bad := range []string{ "", "not-a-hash", "$argon2id$v=19$m=65536,t=1,p=4$onlyfourparts", "$argon2i$v=19$m=65536,t=1,p=4$c2FsdA$aGFzaA", // wrong variant "$argon2id$v=1$m=65536,t=1,p=4$c2FsdA$aGFzaA", // wrong version } { if _, err := verifyPassword(bad, "whatever"); err == nil { t.Errorf("verifyPassword(%q) err = nil, want errBadHash", bad) } } }