package postgres import ( "context" "errors" "strings" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgtype" "lincodex/backend/internal/adapter/secondary/postgres/sqlc" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) // consentDetailMarker stands for a row value that a PostgreSQL detail can // quote, such as the subject or the field set. const consentDetailMarker = "Key (subject_id)=(01928f7a-0000-7000-8000-00000000c0de)" func TestMapConsentErrorRecognizesLedgerConstraints(t *testing.T) { for _, test := range []struct { code string constraint string want error }{ {code: foreignKeyViolationCode, constraint: "consent_records_subject_id_fkey", want: outbound.ErrUserNotFound}, {code: foreignKeyViolationCode, constraint: "consent_records_text_fkey", want: outbound.ErrConsentTextNotFound}, {code: foreignKeyViolationCode, constraint: "consent_records_published_text_fkey", want: outbound.ErrConsentTextMismatch}, {code: checkViolationCode, constraint: "consent_records_text_published", want: outbound.ErrConsentTextNotPublished}, {code: checkViolationCode, constraint: "consent_records_c4_text_hash", want: outbound.ErrConsentTextMismatch}, {code: checkViolationCode, constraint: "consent_records_revocation_stamp", want: domain.ErrInvalidConsent}, {code: integrityConstraintViolationCode, constraint: "consent_records_retained", want: outbound.ErrConsentRecordImmutable}, {code: integrityConstraintViolationCode, constraint: "consent_records_immutable", want: outbound.ErrConsentRecordImmutable}, } { err := mapConsentError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: consentDetailMarker}) if !errors.Is(err, test.want) { t.Fatalf("mapConsentError(%s %s) = %v, want %v", test.code, test.constraint, err, test.want) } if !strings.Contains(err.Error(), test.constraint) || strings.Contains(err.Error(), "subject_id)=") { t.Fatalf("mapConsentError(%s) = %v, want the constraint name and no detail", test.constraint, err) } } } func TestMapConsentErrorDropsDetailOfOtherErrors(t *testing.T) { // A CHECK violation that the domain should have prevented keeps only the // SQLSTATE and the constraint, never the failing row. original := &pgconn.PgError{Code: checkViolationCode, ConstraintName: "consent_records_c4_scope", Detail: "Failing row contains (" + consentDetailMarker + ", {email,phone})."} err := mapConsentError(original) var stateError sqlStateError if !errors.As(err, &stateError) || stateError.SQLState() != checkViolationCode { t.Fatalf("mapConsentError() = %v, want SQLSTATE %s", err, checkViolationCode) } if strings.Contains(err.Error(), "Failing row") || strings.Contains(err.Error(), "phone") { t.Fatalf("mapConsentError() = %v, want no row values", err) } if err := mapConsentError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(err, outbound.ErrTransactionConflict) { t.Fatalf("mapConsentError(deadlock) = %v, want ErrTransactionConflict", err) } if err := mapConsentError(context.Canceled); !errors.Is(err, context.Canceled) { t.Fatalf("mapConsentError(context.Canceled) = %v, want the original error", err) } } func TestConsentLedgerRejectsInvalidInputBeforeQuerying(t *testing.T) { // A ledger without queries proves that no statement runs. ledger := consentLedger{} ctx := t.Context() subject := uuid.Must(uuid.NewV7()) if _, _, err := ledger.Grant(ctx, domain.ConsentGrant{}); !errors.Is(err, domain.ErrInvalidConsent) { t.Fatalf("Grant(zero grant) error = %v, want ErrInvalidConsent", err) } if _, _, err := ledger.GrantContact(ctx, domain.ContactConsentGrant{}); !errors.Is(err, domain.ErrInvalidConsent) { t.Fatalf("GrantContact(zero grant) error = %v, want ErrInvalidConsent", err) } if _, err := ledger.Revoke(ctx, domain.ConsentRevocation{}); !errors.Is(err, domain.ErrInvalidConsent) { t.Fatalf("Revoke(zero revocation) error = %v, want ErrInvalidConsent", err) } if _, err := ledger.Current(ctx, subject, domain.ConsentPurposeContactDisclosure); !errors.Is(err, domain.ErrInvalidConsent) { t.Fatalf("Current(C4) error = %v, want ErrInvalidConsent", err) } if _, err := ledger.Current(ctx, subject, "c9"); !errors.Is(err, domain.ErrInvalidConsent) { t.Fatalf("Current(unknown purpose) error = %v, want ErrInvalidConsent", err) } for _, query := range []outbound.ConsentListQuery{ {Limit: 10}, {SubjectID: subject, Limit: 0}, {SubjectID: subject, Limit: outbound.MaxConsentPageSize + 1}, {SubjectID: subject, Limit: 10, State: "pending"}, {SubjectID: subject, Limit: 10, After: &outbound.ConsentListPosition{ID: subject}}, } { if _, err := ledger.List(ctx, query); !errors.Is(err, domain.ErrInvalidConsent) { t.Fatalf("List(%+v) error = %v, want ErrInvalidConsent", query, err) } } if _, err := (consentTextRepository{}).Current(ctx, domain.ConsentPurposePersonalData, time.Time{}); !errors.Is(err, domain.ErrInvalidConsentText) { t.Fatalf("ConsentTexts.Current(zero time) error = %v, want ErrInvalidConsentText", err) } } // Every record query returns the same columns, so each generated row type // converts to consentRecordRow. A query that changes its columns breaks this // test at compile time instead of mapping a column wrongly. var ( _ = consentRecordRow(sqlc.InsertConsentRecordRow{}) _ = consentRecordRow(sqlc.InsertContactConsentRecordRow{}) _ = consentRecordRow(sqlc.GetUnrevokedConsentRecordByVersionRow{}) _ = consentRecordRow(sqlc.GetContactConsentRecordByInvitationRow{}) _ = consentRecordRow(sqlc.GetCurrentConsentRecordRow{}) _ = consentRecordRow(sqlc.ListCurrentContactConsentRecordsRow{}) _ = consentRecordRow(sqlc.RevokeConsentRecordsRow{}) _ = consentRecordRow(sqlc.RevokeContactConsentRecordsRow{}) _ = consentRecordRow(sqlc.ListConsentRecordsRow{}) ) func TestConsentRecordFromRowMapsNullableScope(t *testing.T) { grantedAt := time.Date(2026, 10, 6, 9, 30, 0, 0, time.UTC) hash := domain.HashConsentText("shown text") subject := uuid.Must(uuid.NewV7()) organization := uuid.Must(uuid.NewV7()) invitation := uuid.Must(uuid.NewV7()) contact, err := consentRecordFromRow(consentRecordRow{ ID: pgUUID(uuid.Must(uuid.NewV7())), SubjectID: pgUUID(subject), Purpose: "c4", TextVersion: "c4-2026-10-01", TextHash: hash[:], Source: "invitation_acceptance", OrganizationID: pgUUID(organization), OrganizationName: pgtype.Text{String: "Acme", Valid: true}, FieldSet: []string{"email", "phone"}, InvitationID: pgUUID(invitation), InvitationTermsVersion: pgtype.Int8{Int64: 3, Valid: true}, GrantedAt: pgTime(grantedAt), RevokedAt: pgTime(grantedAt.Add(time.Hour)), RevocationSource: pgtype.Text{String: "consent_settings", Valid: true}, State: "revoked", }) if err != nil { t.Fatalf("consentRecordFromRow(C4) error = %v", err) } if contact.OrganizationID() != organization || contact.OrganizationName() != "Acme" || contact.InvitationID() != invitation || contact.InvitationTermsVersion() != 3 || !contact.Fields().Contains(domain.ContactFieldPhone) || contact.Fields().Contains(domain.ContactFieldFullName) { t.Fatalf("C4 scope = %s, %s, %d, %v; want the stored scope", contact.OrganizationID(), contact.InvitationID(), contact.InvitationTermsVersion(), contact.Fields().Fields()) } if revokedAt, revoked := contact.RevokedAt(); !revoked || !revokedAt.Equal(grantedAt.Add(time.Hour)) || contact.RevocationSource() != domain.ConsentRevocationSourceConsentSettings { t.Fatalf("revocation = %v %v %q, want the stored stamp", revokedAt, revoked, contact.RevocationSource()) } personalData, err := consentRecordFromRow(consentRecordRow{ ID: pgUUID(uuid.Must(uuid.NewV7())), SubjectID: pgUUID(subject), Purpose: "c1", TextVersion: "c1-2026-10-01", TextHash: hash[:], Source: "registration", GrantedAt: pgTime(grantedAt), State: "active", }) if err != nil { t.Fatalf("consentRecordFromRow(C1) error = %v", err) } if personalData.OrganizationID() != uuid.Nil || !personalData.Fields().IsZero() || personalData.InvitationID() != uuid.Nil { t.Fatalf("C1 scope = %s %v %s, want none", personalData.OrganizationID(), personalData.Fields().Fields(), personalData.InvitationID()) } if _, revoked := personalData.RevokedAt(); revoked || personalData.State() != domain.ConsentStateActive { t.Fatalf("C1 state = %s, want active and unrevoked", personalData.State()) } // A row changed outside the application fails instead of producing a // record that breaks the ledger rules. if _, err := consentRecordFromRow(consentRecordRow{ ID: pgUUID(uuid.Must(uuid.NewV7())), SubjectID: pgUUID(subject), Purpose: "c2", TextVersion: "c2-2026-10-01", TextHash: hash[:], Source: "consent_settings", OrganizationID: pgUUID(organization), GrantedAt: pgTime(grantedAt), State: "active", }); !errors.Is(err, domain.ErrInvalidConsent) { t.Fatalf("consentRecordFromRow(C2 with an organization) error = %v, want ErrInvalidConsent", err) } } func TestContactFieldStringsKeepsCanonicalOrder(t *testing.T) { set, err := domain.NewContactFieldSet(domain.ContactFieldTelegram, domain.ContactFieldFullName, domain.ContactFieldEmail) if err != nil { t.Fatalf("NewContactFieldSet() error = %v", err) } // The migration's consent_field_set_is_canonical accepts only ascending // byte order, the order of PostgreSQL's "C" collation. if got, want := strings.Join(contactFieldStrings(set), ","), "email,full_name,telegram"; got != want { t.Fatalf("contactFieldStrings() = %s, want %s", got, want) } } func TestMapCleanupErrorReportsAConcurrentConsentAsARetryableConflict(t *testing.T) { concurrent := mapCleanupError(&pgconn.PgError{Code: restrictViolationCode, ConstraintName: consentSubjectForeignKey, Detail: consentDetailMarker}) if !errors.Is(concurrent, outbound.ErrTransactionConflict) || strings.Contains(concurrent.Error(), "subject_id)=") { t.Fatalf("mapCleanupError(restrict) = %v, want ErrTransactionConflict without the detail", concurrent) } // Another restricting key, or the same key with another code, is no // conflict. for _, original := range []*pgconn.PgError{ {Code: restrictViolationCode, ConstraintName: "other_fkey"}, {Code: foreignKeyViolationCode, ConstraintName: consentSubjectForeignKey}, } { if err := mapCleanupError(original); errors.Is(err, outbound.ErrTransactionConflict) { t.Fatalf("mapCleanupError(%s %s) = %v, want no conflict", original.Code, original.ConstraintName, err) } } }