package identity import ( "bytes" "context" "errors" "log/slog" "strings" "testing" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) // countingHasher records calls so a test can prove that validation stops a // password before any hashing. type countingHasher struct { hashCalls int hashed domain.Password } func (hasher *countingHasher) Hash(_ context.Context, password domain.Password) (domain.PasswordHash, error) { hasher.hashCalls++ hasher.hashed = password return domain.NewPasswordHash("$argon2id$v=19$m=65536,t=3,p=4$c2FsdHNhbHRzYWx0c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaGhhc2g") } func (hasher *countingHasher) Verify(context.Context, domain.Password, domain.PasswordHash) (bool, error) { return false, errors.New("countingHasher.Verify - not used") } func (hasher *countingHasher) VerifyDummy(context.Context, domain.Password) error { return errors.New("countingHasher.VerifyDummy - not used") } var _ outbound.PasswordHasher = (*countingHasher)(nil) func TestHashNewPasswordRefusesAnOversizedPasswordBeforeHashing(t *testing.T) { const marker = "do-not-log-this-password-" tests := map[string]string{ "129 code points": marker + strings.Repeat("x", 129-len(marker)), "over the raw byte cap": marker + strings.Repeat("\U0001F600", 200), "one megabyte": marker + strings.Repeat("y", 1<<20), "too long after normalization": marker + strings.Repeat("fi", 60), } for name, raw := range tests { hasher := &countingHasher{} var logs bytes.Buffer // The handling boundary logs the error as an HTTP handler would. logger := slog.New(slog.NewJSONHandler(&logs, nil)) _, err := NewCredentials(hasher).HashNewPassword(context.Background(), raw) logger.Error("registration refused", "error", err) if !errors.Is(err, domain.ErrInvalidPassword) { t.Fatalf("HashNewPassword(%s) error = %v, want ErrInvalidPassword", name, err) } if hasher.hashCalls != 0 { t.Fatalf("HashNewPassword(%s) called the hasher %d times, want none", name, hasher.hashCalls) } if strings.Contains(logs.String(), marker) || strings.Contains(err.Error(), marker) { t.Fatalf("HashNewPassword(%s) exposed the input in the error or the log: %s", name, logs.String()) } } } func TestHashNewPasswordRefusesAShortPasswordBeforeHashing(t *testing.T) { hasher := &countingHasher{} _, err := NewCredentials(hasher).HashNewPassword(context.Background(), "fourteen chars") if !errors.Is(err, domain.ErrInvalidPassword) || hasher.hashCalls != 0 { t.Fatalf("HashNewPassword(14 code points) = %v after %d hash calls, want ErrInvalidPassword and no call", err, hasher.hashCalls) } } func TestHashNewPasswordHashesTheNormalizedPassword(t *testing.T) { hasher := &countingHasher{} if _, err := NewCredentials(hasher).HashNewPassword(context.Background(), "correct horse battery"); err != nil { t.Fatalf("HashNewPassword() error = %v", err) } if hasher.hashCalls != 1 || hasher.hashed.Reveal() != "correct horse battery" { t.Fatalf("hasher received %d calls, want one with the NFKC form", hasher.hashCalls) } }