package auth import ( "errors" "strings" "testing" "time" "golang.org/x/crypto/bcrypt" ) func TestPasswordRoundTrip(t *testing.T) { hash, err := HashPassword("correct horse battery staple") if err != nil { t.Fatalf("HashPassword() error = %v", err) } if !VerifyPassword(hash, "correct horse battery staple") { t.Fatal("VerifyPassword() rejected the original password") } if VerifyPassword(hash, "wrong password") { t.Fatal("VerifyPassword() accepted the wrong password") } if cost, err := bcrypt.Cost([]byte(strings.TrimPrefix(hash, bcryptScheme))); err != nil || cost != BcryptCost { t.Fatalf("bcrypt cost = %d, error = %v; want %d", cost, err, BcryptCost) } } func TestNewSessionToken(t *testing.T) { raw, hash, err := NewSessionToken() if err != nil { t.Fatalf("NewSessionToken() error = %v", err) } if raw == "" || hash == "" { t.Fatal("NewSessionToken() returned an empty token or hash") } if got := HashToken(raw); got != hash { diff := got t.Fatalf("HashToken(raw) = %q, want %q", diff, hash) } } func TestResetManagerRoundTrip(t *testing.T) { manager := NewResetManager() code, err := manager.Request() if err != nil { t.Fatalf("Request() error = %v", err) } if len(code) != 8 || strings.ToUpper(code) != code { t.Fatalf("reset code = %q, want eight uppercase characters", code) } if !manager.Confirm(" " + strings.ToLower(code) + " ") { t.Fatal("Confirm() rejected a valid reset code") } if manager.Confirm(code) { t.Fatal("Confirm() accepted a reset code twice") } } func TestResetManagerExpiresCode(t *testing.T) { manager := NewResetManager() if _, err := manager.Request(); err != nil { t.Fatalf("Request() error = %v", err) } manager.mu.Lock() manager.expiresAt = time.Now().Add(-time.Second) manager.mu.Unlock() if manager.Confirm("anything") { t.Fatal("Confirm() accepted an expired reset code") } } func TestValidateCredentialsRefusesEmptyHashAndAtUsername(t *testing.T) { if err := validateCredentials("alice", ""); !errors.Is(err, ErrEmptyPasswordHash) { t.Fatalf("empty hash error = %v, want ErrEmptyPasswordHash", err) } if err := validateCredentials("alice@example.com", "hash"); !errors.Is(err, ErrInvalidUsername) { t.Fatalf("@ username error = %v, want ErrInvalidUsername", err) } if err := validateCredentials("alice", "hash"); err != nil { t.Fatalf("valid credentials refused: %v", err) } } func TestHashPasswordUsesTheSharedBcryptCost(t *testing.T) { hash, err := HashPassword("correct horse battery staple") if err != nil { t.Fatal(err) } cost, err := bcrypt.Cost([]byte(strings.TrimPrefix(hash, bcryptScheme))) if err != nil { t.Fatal(err) } if cost != BcryptCost { t.Fatalf("bcrypt cost = %d, want %d", cost, BcryptCost) } }