package postgres import ( "context" "errors" "fmt" "strings" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" "lincodex/backend/internal/adapter/secondary/postgres/sqlc" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) func TestMapIdentityErrorRecognizesIdentityConstraints(t *testing.T) { tests := []struct { code string constraint string want error }{ {code: uniqueViolationCode, constraint: "users_email_normalized_key", want: outbound.ErrEmailTaken}, {code: uniqueViolationCode, constraint: "email_tokens_token_hash_key", want: outbound.ErrTokenHashConflict}, {code: uniqueViolationCode, constraint: "sessions_token_hash_key", want: outbound.ErrTokenHashConflict}, {code: foreignKeyViolationCode, constraint: "email_tokens_user_id_fkey", want: outbound.ErrUserNotFound}, {code: foreignKeyViolationCode, constraint: "sessions_user_id_fkey", want: outbound.ErrUserNotFound}, } for _, test := range tests { err := mapIdentityError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: "Key (x)=(secret) already exists."}) if !errors.Is(err, test.want) { t.Fatalf("mapIdentityError(%s %s) = %v, want %v", test.code, test.constraint, err, test.want) } if !strings.Contains(err.Error(), test.constraint) || strings.Contains(err.Error(), "secret") { t.Fatalf("mapIdentityError(%s) = %v, want the constraint name and no detail", test.constraint, err) } } } func TestMapIdentityErrorDropsMessageAndDetailOfOtherPostgreSQLErrors(t *testing.T) { original := fmt.Errorf("wrapped: %w", &pgconn.PgError{ Code: "23514", ConstraintName: "users_password_hash_format", Message: `new row violates check constraint "users_password_hash_format" for value secret@example.com`, Detail: "Failing row contains (secret@example.com, $argon2id$v=19$...).", }) err := mapIdentityError(original) var pgError *pgconn.PgError if errors.As(err, &pgError) { t.Fatalf("mapIdentityError() kept the PgError: %v", err) } var stateError sqlStateError if !errors.As(err, &stateError) || stateError.SQLState() != "23514" { t.Fatalf("mapIdentityError() = %v, want SQLSTATE 23514", err) } if !strings.Contains(err.Error(), "users_password_hash_format") || strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "argon2id") { t.Fatalf("mapIdentityError() = %q, want only the code and constraint", err) } } func TestMapIdentityErrorKeepsNonPostgreSQLErrors(t *testing.T) { for _, original := range []error{ errors.New(`duplicate key value violates unique constraint "users_email_normalized_key"`), pgx.ErrNoRows, context.Canceled, } { if err := mapIdentityError(original); err != original { //nolint:errorlint // Identity is the property under test. t.Fatalf("mapIdentityError(%v) = %v, want the original error", original, err) } } } func TestMarkTransactionConflictClassifiesDeadlocksAndSerializationFailures(t *testing.T) { for _, original := range []error{ &pgconn.PgError{Code: deadlockDetectedCode}, fmt.Errorf("statement: %w", &pgconn.PgError{Code: serializationFailureCode}), &databaseError{code: deadlockDetectedCode}, mapIdentityError(&pgconn.PgError{Code: serializationFailureCode}), } { err := markTransactionConflict(original) if !errors.Is(err, outbound.ErrTransactionConflict) || !errors.Is(err, original) { t.Fatalf("markTransactionConflict(%v) = %v, want ErrTransactionConflict wrapping the original", original, err) } if strings.Count(markTransactionConflict(err).Error(), "markTransactionConflict") != 1 { t.Fatalf("markTransactionConflict() wrapped an already classified error again: %v", markTransactionConflict(err)) } } for _, original := range []error{ nil, &pgconn.PgError{Code: uniqueViolationCode}, &pgconn.PgError{Code: "55P03"}, errors.New("connection reset"), } { if err := markTransactionConflict(original); err != original { //nolint:errorlint // Identity is the property under test. t.Fatalf("markTransactionConflict(%v) = %v, want the original error", original, err) } } } func TestIdentityStoreRefusesATransactionContext(t *testing.T) { // A nil pool proves that the guard runs before any statement. store := &IdentityStore{queries: sqlc.New(standaloneDB{})} ctx := context.WithValue(t.Context(), transactionContextKey{}, true) at := time.Now() checks := map[string]error{ "GetByID": errorOf(store.Users().GetByID(ctx, uuid.New())), "DeleteUnverifiedRegisteredBefore": errorOf(store.Users().DeleteUnverifiedRegisteredBefore(ctx, at, 1)), "Consume": errorOf(store.EmailTokens().Consume(ctx, domain.SecretTokenHash{1}, domain.EmailTokenPurposeEmailVerification, at)), "InvalidateActive": errorOf(store.EmailTokens().InvalidateActive(ctx, uuid.New(), domain.EmailTokenPurposeEmailVerification, at)), "Touch": store.Sessions().Touch(ctx, uuid.New(), at, time.Hour), } for name, err := range checks { if !errors.Is(err, outbound.ErrNestedTransaction) { t.Fatalf("%s() error = %v, want ErrNestedTransaction", name, err) } } } // errorOf drops the value of a two-result call. func errorOf[T any](_ T, err error) error { return err } func TestRepositoriesRejectInvalidInputBeforeTheDatabase(t *testing.T) { // A nil query set proves that validation happens before any statement. ctx := t.Context() users, tokens, sessions := userRepository{}, emailTokenRepository{}, sessionRepository{} now, id, hash := time.Now(), uuid.New(), domain.SecretTokenHash{1} purpose := domain.EmailTokenPurposeEmailVerification checks := []struct { name string err error want error }{ {name: "Create(zero user)", err: users.Create(ctx, domain.User{}), want: domain.ErrInvalidUser}, {name: "MarkEmailVerified(zero time)", err: errorOf(users.MarkEmailVerified(ctx, id, 1, time.Time{})), want: domain.ErrInvalidUser}, {name: "DeleteUnverifiedRegisteredBefore(zero cutoff)", err: errorOf(users.DeleteUnverifiedRegisteredBefore(ctx, time.Time{}, 1)), want: domain.ErrInvalidUser}, {name: "Insert(zero token)", err: tokens.Insert(ctx, domain.EmailToken{}), want: domain.ErrInvalidEmailToken}, {name: "Consume(zero time)", err: errorOf(tokens.Consume(ctx, hash, purpose, time.Time{})), want: domain.ErrInvalidEmailToken}, {name: "InvalidateActive(zero time)", err: errorOf(tokens.InvalidateActive(ctx, id, purpose, time.Time{})), want: domain.ErrInvalidEmailToken}, {name: "Create(zero session)", err: sessions.Create(ctx, domain.Session{}), want: domain.ErrInvalidSession}, {name: "FindActive(zero idle timeout)", err: errorOf(sessions.FindActive(ctx, hash, now, 0)), want: domain.ErrInvalidSession}, {name: "FindActive(zero time)", err: errorOf(sessions.FindActive(ctx, hash, time.Time{}, time.Hour)), want: domain.ErrInvalidSession}, {name: "Touch(negative idle timeout)", err: sessions.Touch(ctx, id, now, -time.Second), want: domain.ErrInvalidSession}, {name: "Touch(zero time)", err: sessions.Touch(ctx, id, time.Time{}, time.Hour), want: domain.ErrInvalidSession}, {name: "Revoke(zero time)", err: sessions.Revoke(ctx, id, time.Time{}), want: domain.ErrInvalidSession}, {name: "RevokeAllForUser(zero time)", err: errorOf(sessions.RevokeAllForUser(ctx, id, time.Time{})), want: domain.ErrInvalidSession}, } for _, check := range checks { if !errors.Is(check.err, check.want) { t.Fatalf("%s error = %v, want %v", check.name, check.err, check.want) } } if _, err := users.DeleteUnverifiedRegisteredBefore(ctx, now, 0); err == nil { t.Fatal("DeleteUnverifiedRegisteredBefore(limit 0) error = nil, want an error") } }