package auth import "testing" func TestHashAndVerifyPassword(t *testing.T) { hash, err := HashPassword("correct horse battery staple") if err != nil { t.Fatalf("HashPassword: %v", err) } ok, err := VerifyPassword("correct horse battery staple", hash) if err != nil { t.Fatalf("VerifyPassword: %v", err) } if !ok { t.Fatal("VerifyPassword returned false for the correct password") } } func TestVerifyPasswordRejectsWrongPassword(t *testing.T) { hash, err := HashPassword("correct horse battery staple") if err != nil { t.Fatalf("HashPassword: %v", err) } ok, err := VerifyPassword("wrong password", hash) if err != nil { t.Fatalf("VerifyPassword: %v", err) } if ok { t.Fatal("VerifyPassword returned true for the wrong password") } } func TestVerifyPasswordRejectsMalformedHash(t *testing.T) { if _, err := VerifyPassword("anything", "not-a-hash"); err != ErrInvalidHash { t.Fatalf("VerifyPassword error = %v, want ErrInvalidHash", err) } } func TestHashPasswordProducesUniqueSalts(t *testing.T) { h1, err := HashPassword("same password") if err != nil { t.Fatalf("HashPassword: %v", err) } h2, err := HashPassword("same password") if err != nil { t.Fatalf("HashPassword: %v", err) } if h1 == h2 { t.Fatal("two hashes of the same password should differ due to random salts") } } func TestGenerateAPIKeyAndHash(t *testing.T) { k1, err := GenerateAPIKey() if err != nil { t.Fatalf("GenerateAPIKey: %v", err) } k2, err := GenerateAPIKey() if err != nil { t.Fatalf("GenerateAPIKey: %v", err) } if k1 == k2 { t.Fatal("two generated API keys should differ") } if HashAPIKey(k1) == HashAPIKey(k2) { t.Fatal("hashes of two different keys should differ") } if HashAPIKey(k1) != HashAPIKey(k1) { t.Fatal("hashing the same key twice should be stable") } }