//go:build integration package integration_test import ( "context" "errors" "fmt" "slices" "sync" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) const ( consentTestTimeout = 3 * time.Minute // consentDemoVersionSuffix completes the version of every demo text that // migration 00009 publishes, such as "c1-2026-10-01". consentDemoVersionSuffix = "-2026-10-01" // consentSecondC1Body is a later C1 text that the test publishes the // way a migration would, as consentSecondC1Version. consentSecondC1Body = "I consent to the processing of my personal data, version two." consentOrganizationName = "Acme Synthetic LLC" consentPageSize = 10 // concurrentConsentGrants grants one version at once, each on its own // connection. concurrentConsentGrants = 8 consentRaceRounds = 20 consentCheckViolation = "23514" consentForeignKeyViolation = "23503" consentIntegrityViolation = "23000" // consentRestrictViolation is raised by ON DELETE RESTRICT. consentRestrictViolation = "23001" ) const consentSecondC1Version domain.ConsentTextVersion = "c1-2026-10-05" var ( consentRecordsTable = pgx.Identifier{"consent_records"} accountDeletionRequestsTable = pgx.Identifier{"account_deletion_requests"} // consentTables reference users, so every TRUNCATE of users names them. consentTables = []pgx.Identifier{consentRecordsTable, accountDeletionRequestsTable} ) // consentFixture works on the bootstrap database. The ledger rows are // truncated between subtests; the published texts are immutable and shared. type consentFixture struct { ctx context.Context pool *pgxpool.Pool identity identityFixture store *postgresadapter.ConsentStore transactor *postgresadapter.Transactor // now is a fixed application time after every published text, truncated // to microseconds like the stored times. now time.Time } func TestConsentLedger(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), consentTestTimeout) defer cancel() pool := env.newPool(ctx, t) now := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) fixture := consentFixture{ ctx: ctx, pool: pool, identity: identityFixture{ ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now, }, store: postgresadapter.NewConsentStore(pool), transactor: postgresadapter.NewTransactor(pool), now: now, } // A second C1 text, published as a migration would publish it. if _, err := pool.Exec(ctx, ` INSERT INTO consent_texts (purpose, version, body, body_sha256, kind, published_at) VALUES ('c1', $1, $2, sha256(convert_to($2, 'UTF8')), 'demo', $3)`, string(consentSecondC1Version), consentSecondC1Body, now.Add(-24*time.Hour)); err != nil { t.Fatalf("publish the second C1 text: %v", err) } reset := func(t *testing.T) { t.Helper() // Every table that references users must be truncated with it. truncateTables(ctx, t, pool, usersDependentTables...) } t.Run("migration publishes one demo text per purpose bound to its hash", func(t *testing.T) { texts := fixture.store.ConsentTexts() for _, purpose := range []domain.ConsentPurpose{"c2", "c3", "c4", "c5"} { text, err := texts.Current(ctx, purpose, now) if err != nil { t.Fatalf("Current(%s) error = %v", purpose, err) } if string(text.Version()) != string(purpose)+consentDemoVersionSuffix || text.Kind() != domain.ConsentTextKindDemo || text.Hash() != domain.HashConsentText(text.Body()) { t.Fatalf("Current(%s) = %s %s %x, want the demo text with its hash", purpose, text.Version(), text.Kind(), text.Hash()) } } current, err := texts.Current(ctx, domain.ConsentPurposePersonalData, now) if err != nil || current.Version() != consentSecondC1Version { t.Fatalf("Current(c1) = %s, %v, want the later publication", current.Version(), err) } first, err := texts.Current(ctx, domain.ConsentPurposePersonalData, now.Add(-48*time.Hour)) if err != nil || first.Version() != "c1-2026-10-01" { t.Fatalf("Current(c1, before the second text) = %s, %v, want c1-2026-10-01", first.Version(), err) } if _, err := texts.Current(ctx, domain.ConsentPurposePersonalData, time.Date(2026, 9, 30, 0, 0, 0, 0, time.UTC)); !errors.Is(err, outbound.ErrConsentTextNotFound) { t.Fatalf("Current(before every text) error = %v, want ErrConsentTextNotFound", err) } if _, err := texts.Get(ctx, domain.ConsentPurposePublication, "c2-1999-01-01"); !errors.Is(err, outbound.ErrConsentTextNotFound) { t.Fatalf("Get(unknown version) error = %v, want ErrConsentTextNotFound", err) } // A version belongs to its purpose. if _, err := texts.Get(ctx, domain.ConsentPurposePublication, "c1-2026-10-01"); !errors.Is(err, outbound.ErrConsentTextNotFound) { t.Fatalf("Get(version of another purpose) error = %v, want ErrConsentTextNotFound", err) } }) t.Run("versions and purposes keep their own history", func(t *testing.T) { reset(t) subject := fixture.identity.createUser(t, "history@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) ledger := fixture.store.ConsentLedger() firstC1 := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-72*time.Hour)) publication := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePublication, "c2-2026-10-01", domain.ConsentSourceConsentSettings, now.Add(-2*time.Hour)) before := fixture.rawRecord(t, firstC1.ID()) secondC1 := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePersonalData, consentSecondC1Version, domain.ConsentSourceConsentSettings, now.Add(-time.Hour)) if before != fixture.rawRecord(t, firstC1.ID()) { t.Fatal("a newer version changed the stored record of the earlier version") } current, err := ledger.Current(ctx, subject.ID, domain.ConsentPurposePersonalData) if err != nil || current.ID() != secondC1.ID() { t.Fatalf("Current(c1) = %s, %v, want the newer version", current, err) } page := fixture.list(t, subject.ID, "") assertConsentIDs(t, page.Records, secondC1.ID(), publication.ID(), firstC1.ID()) assertConsentStates(t, page, domain.ConsentStateActive, domain.ConsentStateActive, domain.ConsentStateSuperseded) // Repeating a grant of a version that is still unrevoked stores nothing. grant := fixture.newGrant(t, subject.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceConsentSettings, now) repeated, created, err := ledger.Grant(ctx, grant) if err != nil || created || repeated.ID() != firstC1.ID() || repeated.State() != domain.ConsentStateSuperseded { t.Fatalf("Grant(repeat) = %s, %v, %v, want the existing superseded record", repeated, created, err) } assertRowCount(ctx, t, pool, consentRecordsTable, 3) // Purposes are independent: revoking C2 leaves C1 as it was. revoked := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposePublication, uuid.Nil, now) assertConsentIDs(t, revoked, publication.ID()) if current, err := ledger.Current(ctx, subject.ID, domain.ConsentPurposePersonalData); err != nil || current.ID() != secondC1.ID() { t.Fatalf("Current(c1) after revoking C2 = %s, %v, want it unchanged", current, err) } }) t.Run("revocation stamps once and a new grant is a new record", func(t *testing.T) { reset(t) subject := fixture.identity.createUser(t, "revoke@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) ledger := fixture.store.ConsentLedger() first := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposeAutoCategorization, "c3-2026-10-01", domain.ConsentSourceConsentSettings, now.Add(-time.Hour)) revoked := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposeAutoCategorization, uuid.Nil, now) assertConsentIDs(t, revoked, first.ID()) if revokedAt, ok := revoked[0].RevokedAt(); !ok || !revokedAt.Equal(now) || revoked[0].RevocationSource() != domain.ConsentRevocationSourceConsentSettings { t.Fatalf("revocation = %v %v %q, want the stamp", revokedAt, ok, revoked[0].RevocationSource()) } // A repeat finds nothing to revoke and keeps the first stamp. if again := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposeAutoCategorization, uuid.Nil, now.Add(time.Minute)); len(again) != 0 { t.Fatalf("second Revoke() = %v, want nothing", again) } if _, err := ledger.Current(ctx, subject.ID, domain.ConsentPurposeAutoCategorization); !errors.Is(err, outbound.ErrConsentNotFound) { t.Fatalf("Current(revoked) error = %v, want ErrConsentNotFound", err) } regranted := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposeAutoCategorization, "c3-2026-10-01", domain.ConsentSourceConsentSettings, now.Add(2*time.Minute)) if regranted.ID() == first.ID() { t.Fatal("a grant after a revocation reused the revoked record") } page := fixture.list(t, subject.ID, "") assertConsentIDs(t, page.Records, regranted.ID(), first.ID()) assertConsentStates(t, page, domain.ConsentStateActive, domain.ConsentStateRevoked) if revokedAt, _ := page.Records[1].RevokedAt(); !revokedAt.Equal(now) { t.Fatalf("revoked record stamp = %v, want the first revocation %v", revokedAt, now) } // Revoking a purpose closes superseded records too. olderC1 := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-48*time.Hour)) newerC1 := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePersonalData, consentSecondC1Version, domain.ConsentSourceConsentSettings, now) closed := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposePersonalData, uuid.Nil, now.Add(time.Hour)) if len(closed) != 2 || !slices.ContainsFunc(closed, func(r domain.ConsentRecord) bool { return r.ID() == olderC1.ID() }) || !slices.ContainsFunc(closed, func(r domain.ConsentRecord) bool { return r.ID() == newerC1.ID() }) { t.Fatalf("Revoke(c1) = %v, want both C1 records", closed) } }) t.Run("C4 requires its scope and records it once per invitation", func(t *testing.T) { reset(t) subject := fixture.identity.createUser(t, "contact@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) other := fixture.identity.createUser(t, "other-contact@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) ledger := fixture.store.ConsentLedger() organization, otherOrganization := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()) invitation := uuid.Must(uuid.NewV7()) // The generic grant refuses C4, and the scoped grant refuses a missing scope. if _, err := domain.NewConsentGrant(domain.ConsentGrantInput{ SubjectID: subject.ID, Purpose: domain.ConsentPurposeContactDisclosure, TextVersion: "c4-2026-10-01", TextHash: domain.HashConsentText("x"), Source: domain.ConsentSourceInvitationAcceptance, GrantedAt: now, }); !errors.Is(err, domain.ErrInvalidConsent) { t.Fatalf("NewConsentGrant(C4) error = %v, want ErrInvalidConsent", err) } if _, err := domain.NewContactConsentGrant(domain.ContactConsentGrantInput{ SubjectID: subject.ID, OrganizationName: consentOrganizationName, InvitationID: invitation, InvitationTermsVersion: 1, Text: fixture.text(t, domain.ConsentPurposeContactDisclosure), GrantedAt: now, }); !errors.Is(err, domain.ErrInvalidConsent) { t.Fatalf("NewContactConsentGrant(no organization, no fields) error = %v, want ErrInvalidConsent", err) } grant := fixture.newContactGrant(t, subject.ID, organization, invitation, now, domain.ContactFieldPhone, domain.ContactFieldEmail) record, created, err := ledger.GrantContact(ctx, grant) if err != nil || !created { t.Fatalf("GrantContact() = %v, %v, want a new record", created, err) } if record.Purpose() != domain.ConsentPurposeContactDisclosure || record.OrganizationID() != organization || record.OrganizationName() != consentOrganizationName || record.InvitationID() != invitation || record.InvitationTermsVersion() != 2 || record.Source() != domain.ConsentSourceInvitationAcceptance || fmt.Sprint(record.Fields().Fields()) != "[email phone]" || record.TextHash() != grant.TextHash() { t.Fatalf("C4 record = %s with scope %s %s %v, want the granted scope", record, record.OrganizationID(), record.InvitationID(), record.Fields().Fields()) } // The shown text names the organization, so its hash is not the hash // of the published template. template := fixture.text(t, domain.ConsentPurposeContactDisclosure) if record.TextHash() == template.Hash() { t.Fatal("the C4 record must keep the hash of the shown text, not of the template") } repeat := fixture.newContactGrant(t, subject.ID, organization, invitation, now.Add(time.Minute), domain.ContactFieldEmail) again, created, err := ledger.GrantContact(ctx, repeat) if err != nil || created || again.ID() != record.ID() || !again.Fields().Equal(record.Fields()) { t.Fatalf("GrantContact(repeat) = %s, %v, %v, want the existing record unchanged", again, created, err) } taken := fixture.newContactGrant(t, other.ID, organization, invitation, now, domain.ContactFieldEmail) if _, _, err := ledger.GrantContact(ctx, taken); !errors.Is(err, outbound.ErrConsentInvitationTaken) { t.Fatalf("GrantContact(invitation of another subject) error = %v, want ErrConsentInvitationTaken", err) } second := fixture.newContactGrant(t, subject.ID, otherOrganization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldTelegram) secondRecord, _, err := ledger.GrantContact(ctx, second) if err != nil { t.Fatalf("GrantContact(other organization) error = %v", err) } currentA, err := ledger.CurrentContact(ctx, subject.ID, organization) if err != nil { t.Fatalf("CurrentContact(A) error = %v", err) } assertConsentIDs(t, currentA, record.ID()) // C4 is revoked per organization; another organization keeps its consent. revoked := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposeContactDisclosure, organization, now.Add(time.Hour)) assertConsentIDs(t, revoked, record.ID()) if currentA, err := ledger.CurrentContact(ctx, subject.ID, organization); err != nil || len(currentA) != 0 { t.Fatalf("CurrentContact(A) after revocation = %v, %v, want none", currentA, err) } currentB, err := ledger.CurrentContact(ctx, subject.ID, otherOrganization) if err != nil { t.Fatalf("CurrentContact(B) error = %v", err) } assertConsentIDs(t, currentB, secondRecord.ID()) // The revoked invitation consent never comes back as a new grant. comeback, created, err := ledger.GrantContact(ctx, fixture.newContactGrant(t, subject.ID, organization, invitation, now.Add(2*time.Hour), domain.ContactFieldEmail)) if err != nil || created || comeback.State() != domain.ConsentStateRevoked { t.Fatalf("GrantContact(revoked invitation) = %s, %v, %v, want the revoked record", comeback, created, err) } }) t.Run("the repository refuses a foreign subject and unbound texts", func(t *testing.T) { reset(t) subject := fixture.identity.createUser(t, "owner@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) stranger := fixture.identity.createUser(t, "stranger@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) ledger := fixture.store.ConsentLedger() publicationText := fixture.text(t, domain.ConsentPurposePublication) grantWith := func(subjectID uuid.UUID, version domain.ConsentTextVersion, hash domain.ConsentTextHash, at time.Time) error { grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{ SubjectID: subjectID, Purpose: domain.ConsentPurposePublication, TextVersion: version, TextHash: hash, Source: domain.ConsentSourceConsentSettings, GrantedAt: at, }) if err != nil { return err } _, _, err = ledger.Grant(ctx, grant) return err } for _, test := range []struct { name string err error want error }{ {"unknown subject", grantWith(uuid.Must(uuid.NewV7()), publicationText.Version(), publicationText.Hash(), now), outbound.ErrUserNotFound}, {"empty version", grantWith(subject.ID, "", publicationText.Hash(), now), domain.ErrInvalidConsentText}, {"malformed version", grantWith(subject.ID, "c2 2026", publicationText.Hash(), now), domain.ErrInvalidConsentText}, {"empty hash", grantWith(subject.ID, publicationText.Version(), domain.ConsentTextHash{}, now), domain.ErrInvalidConsentText}, {"invented version", grantWith(subject.ID, "c2-2099-01-01", publicationText.Hash(), now), outbound.ErrConsentTextNotFound}, {"version of another purpose", grantWith(subject.ID, "c3-2026-10-01", publicationText.Hash(), now), outbound.ErrConsentTextNotFound}, {"hash of another text", grantWith(subject.ID, publicationText.Version(), domain.HashConsentText("edited text"), now), outbound.ErrConsentTextMismatch}, {"grant before publication", grantWith(subject.ID, publicationText.Version(), publicationText.Hash(), publicationText.PublishedAt().Add(-time.Second)), outbound.ErrConsentTextNotPublished}, } { if !errors.Is(test.err, test.want) { t.Fatalf("Grant(%s) error = %v, want %v", test.name, test.err, test.want) } } assertRowCount(ctx, t, pool, consentRecordsTable, 0) // Reads and revocations are scoped by the subject: the stranger // neither sees nor revokes the owner's consent. owned := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePublication, publicationText.Version(), domain.ConsentSourceConsentSettings, now) if revoked := fixture.revoke(t, ledger, stranger.ID, domain.ConsentPurposePublication, uuid.Nil, now.Add(time.Minute)); len(revoked) != 0 { t.Fatalf("Revoke(stranger) = %v, want nothing", revoked) } if _, err := ledger.Current(ctx, stranger.ID, domain.ConsentPurposePublication); !errors.Is(err, outbound.ErrConsentNotFound) { t.Fatalf("Current(stranger) error = %v, want ErrConsentNotFound", err) } if current, err := ledger.Current(ctx, subject.ID, domain.ConsentPurposePublication); err != nil || current.ID() != owned.ID() { t.Fatalf("Current(owner) = %s, %v, want the owner's record", current, err) } }) t.Run("the database refuses invalid rows written around the repository", func(t *testing.T) { reset(t) subject := fixture.identity.createUser(t, "raw@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) publicationHash := fixture.text(t, domain.ConsentPurposePublication).Hash() insert := func(purpose, version string, hash []byte, source string, organization *uuid.UUID, fields []string, revocation *string) error { var invitation *uuid.UUID var terms *int64 if organization != nil { id, version := uuid.Must(uuid.NewV7()), int64(1) invitation, terms = &id, &version } var revokedAt *time.Time if revocation != nil { revokedAt = &now if *revocation == "" { revocation = nil } } _, err := pool.Exec(ctx, ` INSERT INTO consent_records ( id, subject_id, purpose, text_version, text_hash, source, organization_id, field_set, invitation_id, invitation_terms_version, granted_at, revoked_at, revocation_source ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)`, uuid.Must(uuid.NewV7()), subject.ID, purpose, version, hash, source, organization, fields, invitation, terms, now, revokedAt, revocation) return err } organization := uuid.Must(uuid.NewV7()) empty := "" for _, test := range []struct { name string err error code string constraint string }{ {"empty version", insert("c2", "", publicationHash[:], "consent_settings", nil, nil, nil), consentCheckViolation, "consent_records_text_version_format"}, {"empty hash", insert("c2", "c2-2026-10-01", []byte{}, "consent_settings", nil, nil, nil), consentCheckViolation, "consent_records_text_hash_sha256"}, {"short hash", insert("c2", "c2-2026-10-01", publicationHash[:31], "consent_settings", nil, nil, nil), consentCheckViolation, "consent_records_text_hash_sha256"}, {"C4 without a scope", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", nil, nil, nil), consentCheckViolation, "consent_records_c4_scope"}, {"C4 with an empty field set", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", &organization, []string{}, nil), consentCheckViolation, "consent_records_c4_scope"}, {"C4 with a repeated field", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", &organization, []string{"email", "email"}, nil), consentCheckViolation, "consent_records_c4_scope"}, {"C4 with an unknown field", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", &organization, []string{"address"}, nil), consentCheckViolation, "consent_records_c4_scope"}, {"C2 with a scope", insert("c2", "c2-2026-10-01", publicationHash[:], "consent_settings", &organization, []string{"email"}, nil), consentCheckViolation, "consent_records_c4_scope"}, {"C2 from the registration", insert("c2", "c2-2026-10-01", publicationHash[:], "registration", nil, nil, nil), consentCheckViolation, "consent_records_registration_version"}, {"C2 from an invitation", insert("c2", "c2-2026-10-01", publicationHash[:], "invitation_acceptance", nil, nil, nil), consentCheckViolation, "consent_records_source_of_purpose"}, {"revocation without a source", insert("c2", "c2-2026-10-01", publicationHash[:], "consent_settings", nil, nil, &empty), consentCheckViolation, "consent_records_revocation_stamp"}, {"hash of another text", insert("c3", "c3-2026-10-01", publicationHash[:], "consent_settings", nil, nil, nil), consentForeignKeyViolation, "consent_records_published_text_fkey"}, } { assertSQLError(t, test.name, test.err, test.code, test.constraint) } ledger := fixture.store.ConsentLedger() record := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePublication, "c2-2026-10-01", domain.ConsentSourceConsentSettings, now) _, err := pool.Exec(ctx, `UPDATE consent_records SET text_version = 'c2-2026-10-02' WHERE id = $1`, record.ID()) assertSQLError(t, "update of a granted record", err, consentIntegrityViolation, "consent_records_immutable") _, err = pool.Exec(ctx, `UPDATE consent_records SET revoked_at = granted_at, revocation_source = 'consent_settings', granted_at = granted_at - interval '1 day' WHERE id = $1`, record.ID()) assertSQLError(t, "revocation that also moves the grant", err, consentIntegrityViolation, "consent_records_immutable") fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposePublication, uuid.Nil, now) _, err = pool.Exec(ctx, `UPDATE consent_records SET revoked_at = revoked_at + interval '1 hour' WHERE id = $1`, record.ID()) assertSQLError(t, "second revocation stamp", err, consentIntegrityViolation, "consent_records_immutable") _, err = pool.Exec(ctx, `UPDATE consent_texts SET body = body || '.' WHERE purpose = 'c2'`) assertSQLError(t, "update of a published text", err, consentIntegrityViolation, "consent_texts_immutable") _, err = pool.Exec(ctx, `DELETE FROM consent_texts WHERE purpose = 'c2'`) assertSQLError(t, "delete of a published text", err, consentIntegrityViolation, "consent_texts_immutable") // Consent evidence outlives a careless account delete. _, err = pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, subject.ID) assertSQLError(t, "delete of an account with consent history", err, consentRestrictViolation, "consent_records_subject_id_fkey") }) t.Run("the read model returns only the caller's own records page by page", func(t *testing.T) { reset(t) owner := fixture.identity.createUser(t, "reader@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) stranger := fixture.identity.createUser(t, "neighbour@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) ledger := fixture.store.ConsentLedger() strangerRecord := fixture.grant(t, ledger, stranger.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-30*time.Minute)) var owned []uuid.UUID for index, purpose := range []domain.ConsentPurpose{"c1", "c2", "c3", "c5"} { record := fixture.grant(t, ledger, owner.ID, purpose, domain.ConsentTextVersion(string(purpose)+consentDemoVersionSuffix), domain.ConsentSourceConsentSettings, now.Add(time.Duration(index-10)*time.Minute)) owned = append([]uuid.UUID{record.ID()}, owned...) } fixture.revoke(t, ledger, owner.ID, domain.ConsentPurposeAutoCategorization, uuid.Nil, now) var seen []uuid.UUID query := outbound.ConsentListQuery{SubjectID: owner.ID, Limit: 3} for range 3 { page, err := ledger.List(ctx, query) if err != nil { t.Fatalf("List() error = %v", err) } for _, record := range page.Records { if record.SubjectID() != owner.ID { t.Fatalf("List(owner) returned %s of another subject", record) } seen = append(seen, record.ID()) } if !page.HasMore { break } position := outbound.ConsentPositionOf(page.Records[len(page.Records)-1]) query.After = &position } if !slices.Equal(seen, owned) || slices.Contains(seen, strangerRecord.ID()) { t.Fatalf("pages = %v, want exactly the owner's records newest first %v", seen, owned) } active := fixture.list(t, owner.ID, domain.ConsentStateActive) if len(active.Records) != 3 || slices.ContainsFunc(active.Records, func(r domain.ConsentRecord) bool { return r.Purpose() == domain.ConsentPurposeAutoCategorization }) { t.Fatalf("List(active) = %v, want the three unrevoked purposes", active.Records) } revoked := fixture.list(t, owner.ID, domain.ConsentStateRevoked) if len(revoked.Records) != 1 || revoked.Records[0].Purpose() != domain.ConsentPurposeAutoCategorization { t.Fatalf("List(revoked) = %v, want the revoked C3", revoked.Records) } if empty := fixture.list(t, uuid.Must(uuid.NewV7()), ""); len(empty.Records) != 0 || empty.HasMore { t.Fatalf("List(unknown subject) = %v, want an empty page", empty.Records) } }) t.Run("a C4 grant commits and rolls back with its business transaction", func(t *testing.T) { reset(t) subject := fixture.identity.createUser(t, "accept@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) organization := uuid.Must(uuid.NewV7()) rolledBack := fixture.newContactGrant(t, subject.ID, organization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldEmail) err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if _, created, err := unit.ConsentLedger().GrantContact(ctx, rolledBack); err != nil || !created { return fmt.Errorf("grant inside the acceptance: created %v: %w", created, err) } // A later step of the acceptance fails, for example the state // transition or the contact grant. return errForcedRollback }) if !errors.Is(err, errForcedRollback) { t.Fatalf("WithinTransaction() error = %v, want the forced rollback", err) } assertRowCount(ctx, t, pool, consentRecordsTable, 0) // A failing statement after the grant aborts the whole acceptance. failing := fixture.newContactGrant(t, subject.ID, organization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldEmail) unknownSubject := fixture.newContactGrant(t, uuid.Must(uuid.NewV7()), organization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldEmail) err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if _, _, err := unit.ConsentLedger().GrantContact(ctx, failing); err != nil { return err } _, _, err := unit.ConsentLedger().GrantContact(ctx, unknownSubject) return err }) if !errors.Is(err, outbound.ErrUserNotFound) { t.Fatalf("WithinTransaction(failing step) error = %v, want ErrUserNotFound", err) } assertRowCount(ctx, t, pool, consentRecordsTable, 0) committed := fixture.newContactGrant(t, subject.ID, organization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldEmail, domain.ContactFieldFullName) var record domain.ConsentRecord err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var err error record, _, err = unit.ConsentLedger().GrantContact(ctx, committed) if err != nil { return err } // The same transaction sees its own grant before the commit. current, err := unit.ConsentLedger().CurrentContact(ctx, subject.ID, organization) if err != nil || len(current) != 1 { return fmt.Errorf("read own grant: %d records: %w", len(current), err) } return nil }) if err != nil { t.Fatalf("WithinTransaction(commit) error = %v", err) } current, err := fixture.store.ConsentLedger().CurrentContact(ctx, subject.ID, organization) if err != nil { t.Fatalf("CurrentContact() error = %v", err) } assertConsentIDs(t, current, record.ID()) }) t.Run("the unverified account cleanup removes the ledger of the accounts it deletes", func(t *testing.T) { reset(t) users := fixture.identity.store.Users() ledger := fixture.store.ConsentLedger() cutoff := now.Add(-time.Hour) stale := fixture.identity.createUser(t, "stale-consent@example.com", domain.ScenarioCandidate, cutoff.Add(-time.Hour)) fixture.grant(t, ledger, stale.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, cutoff.Add(-time.Hour)) verified := fixture.identity.createUser(t, "verified-consent@example.com", domain.ScenarioCandidate, cutoff.Add(-2*time.Hour)) kept := fixture.grant(t, ledger, verified.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, cutoff.Add(-2*time.Hour)) if _, err := users.MarkEmailVerified(ctx, verified.ID, verified.RegistrationVersion, cutoff.Add(-90*time.Minute)); err != nil { t.Fatalf("MarkEmailVerified() error = %v", err) } deleted, err := users.DeleteUnverifiedRegisteredBefore(ctx, cutoff, staleAccounts) if err != nil || deleted != 1 { t.Fatalf("DeleteUnverifiedRegisteredBefore() = %d, %v, want 1", deleted, err) } if _, err := users.GetByID(ctx, stale.ID); !errors.Is(err, outbound.ErrUserNotFound) { t.Fatalf("GetByID(stale) error = %v, want ErrUserNotFound", err) } page := fixture.list(t, verified.ID, "") assertConsentIDs(t, page.Records, kept.ID()) assertRowCount(ctx, t, pool, consentRecordsTable, 1) }) t.Run("the database checks the C4 hash against the organization name snapshot", func(t *testing.T) { reset(t) subject := fixture.identity.createUser(t, "snapshot@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) text := fixture.text(t, domain.ConsentPurposeContactDisclosure) shownFor := func(name string) []byte { shown, err := text.RenderForOrganization(name) if err != nil { t.Fatalf("RenderForOrganization(%q) error = %v", name, err) } hash := domain.HashConsentText(shown) return hash[:] } insert := func(purpose, name string, hash []byte) error { var organization, invitation *uuid.UUID var fields []string var terms *int64 source := "consent_settings" version := purpose + consentDemoVersionSuffix if purpose == "c4" { organizationID, invitationID, termsVersion := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()), int64(1) organization, invitation, terms, fields, source = &organizationID, &invitationID, &termsVersion, []string{"email"}, "invitation_acceptance" } _, err := pool.Exec(ctx, ` INSERT INTO consent_records ( id, subject_id, purpose, text_version, text_hash, source, organization_id, organization_name, field_set, invitation_id, invitation_terms_version, granted_at ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`, uuid.Must(uuid.NewV7()), subject.ID, purpose, version, hash, source, organization, name, fields, invitation, terms, now) return err } personalData := fixture.text(t, domain.ConsentPurposePersonalData) personalHash := personalData.Hash() assertSQLError(t, "hash of another organization name", insert("c4", consentOrganizationName, shownFor("Other LLC")), consentCheckViolation, "consent_records_c4_text_hash") assertSQLError(t, "name other than the shown one", insert("c4", "Other LLC", shownFor(consentOrganizationName)), consentCheckViolation, "consent_records_c4_text_hash") templateHash := text.Hash() assertSQLError(t, "hash of the template", insert("c4", consentOrganizationName, templateHash[:]), consentCheckViolation, "consent_records_c4_text_hash") assertSQLError(t, "C4 without a name", func() error { _, err := pool.Exec(ctx, ` INSERT INTO consent_records ( id, subject_id, purpose, text_version, text_hash, source, organization_id, field_set, invitation_id, invitation_terms_version, granted_at ) VALUES ($1, $2, 'c4', 'c4-2026-10-01', $3, 'invitation_acceptance', $4, '{email}', $5, 1, $6)`, uuid.Must(uuid.NewV7()), subject.ID, shownFor(consentOrganizationName), uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()), now) return err }(), consentCheckViolation, "consent_records_c4_scope") assertSQLError(t, "C1 with an organization name", insert("c1", consentOrganizationName, personalHash[:]), consentCheckViolation, "consent_records_c4_scope") if err := insert("c4", consentOrganizationName, shownFor(consentOrganizationName)); err != nil { t.Fatalf("insert the hash of the shown text: %v", err) } // The organization is renamed between two acceptances: each record // keeps the name its own text showed, and its hash still proves that // text. ledger := fixture.store.ConsentLedger() organization := uuid.Must(uuid.NewV7()) before, _, err := ledger.GrantContact(ctx, fixture.newNamedContactGrant(t, consentOrganizationName, subject.ID, organization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldEmail)) if err != nil { t.Fatalf("GrantContact(before the rename) error = %v", err) } const renamed = "Acme Renamed LLC" after, _, err := ledger.GrantContact(ctx, fixture.newNamedContactGrant(t, renamed, subject.ID, organization, uuid.Must(uuid.NewV7()), now.Add(time.Minute), domain.ContactFieldPhone)) if err != nil { t.Fatalf("GrantContact(after the rename) error = %v", err) } current, err := ledger.CurrentContact(ctx, subject.ID, organization) if err != nil { t.Fatalf("CurrentContact() error = %v", err) } assertConsentIDs(t, current, after.ID(), before.ID()) for index, want := range []string{renamed, consentOrganizationName} { record := current[index] if record.OrganizationName() != want { t.Fatalf("record %s name = %q, want the snapshot %q", record, record.OrganizationName(), want) } if hash := record.TextHash(); !slices.Equal(shownFor(record.OrganizationName()), hash[:]) { t.Fatalf("record %s hash does not prove the text shown with its snapshot", record) } } }) t.Run("a revocation before the grant time is stamped at the grant time", func(t *testing.T) { reset(t) subject := fixture.identity.createUser(t, "skew@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) ledger := fixture.store.ConsentLedger() record := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePublication, "c2-2026-10-01", domain.ConsentSourceConsentSettings, now) revoked := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposePublication, uuid.Nil, now.Add(-time.Hour)) assertConsentIDs(t, revoked, record.ID()) if revokedAt, _ := revoked[0].RevokedAt(); !revokedAt.Equal(now) { t.Fatalf("revoked_at = %v, want the grant time %v", revokedAt, now) } }) t.Run("only the consent of an unconfirmed account can be deleted", func(t *testing.T) { reset(t) ledger := fixture.store.ConsentLedger() confirmed := fixture.identity.createUser(t, "confirmed@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) retained := fixture.grant(t, ledger, confirmed.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-72*time.Hour)) if _, err := fixture.identity.store.Users().MarkEmailVerified(ctx, confirmed.ID, confirmed.RegistrationVersion, now.Add(-71*time.Hour)); err != nil { t.Fatalf("MarkEmailVerified() error = %v", err) } unconfirmed := fixture.identity.createUser(t, "unconfirmed@example.com", domain.ScenarioCandidate, now.Add(-time.Hour)) discardable := fixture.grant(t, ledger, unconfirmed.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-time.Hour)) _, err := pool.Exec(ctx, `DELETE FROM consent_records WHERE id = $1`, retained.ID()) assertSQLError(t, "delete of a confirmed account's consent", err, consentIntegrityViolation, "consent_records_retained") if _, err := pool.Exec(ctx, `DELETE FROM consent_records WHERE id = $1`, discardable.ID()); err != nil { t.Fatalf("delete of an unconfirmed account's consent: %v", err) } assertRowCount(ctx, t, pool, consentRecordsTable, 1) }) t.Run("re-registration of an unverified account replaces its registration C1", func(t *testing.T) { reset(t) ledger := fixture.store.ConsentLedger() first := fixture.identity.createUser(t, "reregister@example.com", domain.ScenarioCandidate, now.Add(-2*time.Hour)) earlier := fixture.grant(t, ledger, first.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-2*time.Hour)) changed, err := first.ReRegister(fixture.identity.registration(t, "reregister@example.com", domain.ScenarioEmployer, now)) if err != nil { t.Fatalf("ReRegister() error = %v", err) } var replacement domain.ConsentRecord var registered domain.User err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var err error registered, err = unit.Users().UpdateRegistration(ctx, changed) if err != nil { return err } grant := fixture.newGrant(t, first.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now, registered.RegistrationVersion) var created bool replacement, created, err = unit.ConsentLedger().Grant(ctx, grant) if err == nil && !created { return errors.New("the new registration reused the earlier registrant's C1") } return err }) if err != nil { t.Fatalf("re-registration transaction error = %v", err) } page := fixture.list(t, first.ID, "") assertConsentIDs(t, page.Records, replacement.ID()) if replacement.ID() == earlier.ID() { t.Fatal("the earlier registrant's C1 survived the re-registration") } if replacement.RegistrationVersion() != registered.RegistrationVersion { t.Fatalf("replacement C1 registration version = %d, want %d", replacement.RegistrationVersion(), registered.RegistrationVersion) } // A stale re-registration changes nothing and deletes nothing. if _, err := fixture.identity.store.Users().UpdateRegistration(ctx, changed); !errors.Is(err, outbound.ErrUserVersionConflict) { t.Fatalf("UpdateRegistration(stale) error = %v, want ErrUserVersionConflict", err) } assertConsentIDs(t, fixture.list(t, first.ID, "").Records, replacement.ID()) // A verified account is never re-registered, so its C1 stays. verified := fixture.identity.createUser(t, "verified-reregister@example.com", domain.ScenarioCandidate, now.Add(-2*time.Hour)) kept := fixture.grant(t, ledger, verified.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-2*time.Hour)) if _, err := fixture.identity.store.Users().MarkEmailVerified(ctx, verified.ID, verified.RegistrationVersion, now.Add(-time.Hour)); err != nil { t.Fatalf("MarkEmailVerified() error = %v", err) } stale, err := verified.ReRegister(fixture.identity.registration(t, "verified-reregister@example.com", domain.ScenarioEmployer, now)) if err != nil { t.Fatalf("ReRegister(the unverified copy) error = %v", err) } if _, err := fixture.identity.store.Users().UpdateRegistration(ctx, stale); !errors.Is(err, outbound.ErrUserVersionConflict) { t.Fatalf("UpdateRegistration(verified) error = %v, want ErrUserVersionConflict", err) } assertConsentIDs(t, fixture.list(t, verified.ID, "").Records, kept.ID()) }) t.Run("concurrent grants of one version store one record", func(t *testing.T) { reset(t) subject := fixture.identity.createUser(t, "concurrent@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) ledger := postgresadapter.NewConsentStore(env.newPoolWithMaxConns(ctx, t, concurrentConsentGrants)).ConsentLedger() grants := make([]domain.ConsentGrant, concurrentConsentGrants) for index := range grants { grants[index] = fixture.newGrant(t, subject.ID, domain.ConsentPurposePublication, "c2-2026-10-01", domain.ConsentSourceConsentSettings, now) } records := make([]domain.ConsentRecord, len(grants)) createdFlags := make([]bool, len(grants)) errs := make([]error, len(grants)) start := make(chan struct{}) var group sync.WaitGroup for index, grant := range grants { group.Go(func() { <-start records[index], createdFlags[index], errs[index] = ledger.Grant(ctx, grant) }) } close(start) group.Wait() created := 0 for index, err := range errs { if err != nil { t.Fatalf("Grant %d error = %v", index, err) } if createdFlags[index] { created++ } if records[index].ID() != records[0].ID() { t.Fatalf("Grant %d returned %s, want the one record %s", index, records[index], records[0]) } } if created != 1 { t.Fatalf("%d grants created a record, want exactly 1", created) } assertRowCount(ctx, t, pool, consentRecordsTable, 1) }) t.Run("a grant racing a revocation leaves at most one unrevoked record of the version", func(t *testing.T) { reset(t) subject := fixture.identity.createUser(t, "race@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) ledger := postgresadapter.NewConsentStore(env.newPoolWithMaxConns(ctx, t, 2)).ConsentLedger() fixture.grant(t, ledger, subject.ID, domain.ConsentPurposeFSPImport, "c5-2026-10-01", domain.ConsentSourceConsentSettings, now) for round := range consentRaceRounds { at := now.Add(time.Duration(round+1) * time.Minute) grant := fixture.newGrant(t, subject.ID, domain.ConsentPurposeFSPImport, "c5-2026-10-01", domain.ConsentSourceConsentSettings, at) revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ SubjectID: subject.ID, Purpose: domain.ConsentPurposeFSPImport, Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: at, }) if err != nil { t.Fatalf("NewConsentRevocation() error = %v", err) } var grantErr, revokeErr error start := make(chan struct{}) var group sync.WaitGroup group.Go(func() { <-start; _, _, grantErr = ledger.Grant(ctx, grant) }) group.Go(func() { <-start; _, revokeErr = ledger.Revoke(ctx, revocation) }) close(start) group.Wait() // The only documented race outcome is a conflict the caller retries. if grantErr != nil && !errors.Is(grantErr, outbound.ErrTransactionConflict) { t.Fatalf("round %d Grant() error = %v", round, grantErr) } if revokeErr != nil { t.Fatalf("round %d Revoke() error = %v", round, revokeErr) } var unrevoked int if err := pool.QueryRow(ctx, ` SELECT count(*) FROM consent_records WHERE subject_id = $1 AND purpose = 'c5' AND revoked_at IS NULL`, subject.ID).Scan(&unrevoked); err != nil { t.Fatalf("count unrevoked records: %v", err) } if unrevoked > 1 { t.Fatalf("round %d left %d unrevoked records of one version", round, unrevoked) } } }) t.Run("the cleanup skips an account whose consent row is locked", func(t *testing.T) { reset(t) cutoff := now.Add(-time.Hour) stale := fixture.identity.createUser(t, "locked-consent@example.com", domain.ScenarioCandidate, cutoff.Add(-time.Hour)) fixture.grant(t, fixture.store.ConsentLedger(), stale.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, cutoff.Add(-time.Hour)) // Only the consent row is locked: a revocation in a transaction that // stays open and rolls back. holder := startHeldTransaction(ctx, t, postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, 2)), func(ctx context.Context, unit outbound.UnitOfWork) error { revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ SubjectID: stale.ID, Purpose: domain.ConsentPurposePersonalData, Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: cutoff, }) if err != nil { return err } revoked, err := unit.ConsentLedger().Revoke(ctx, revocation) if err == nil && len(revoked) != 1 { return fmt.Errorf("revoked %d records, want 1", len(revoked)) } return err }, false) holder.awaitHeld(ctx, t) impatient := postgresadapter.NewIdentityStore(env.newPoolWithLockTimeout(ctx, t, cleanupLockTimeout)).Users() deleted, err := impatient.DeleteUnverifiedRegisteredBefore(ctx, cutoff, staleAccounts) if err != nil || deleted != 0 { t.Fatalf("DeleteUnverifiedRegisteredBefore(consent locked) = %d, %v, want 0 without waiting", deleted, err) } if err := holder.finish(); !errors.Is(err, errForcedRollback) { t.Fatalf("holder error = %v, want the forced rollback", err) } deleted, err = impatient.DeleteUnverifiedRegisteredBefore(ctx, cutoff, staleAccounts) if err != nil || deleted != 1 { t.Fatalf("DeleteUnverifiedRegisteredBefore(unlocked) = %d, %v, want 1", deleted, err) } assertRowCount(ctx, t, pool, consentRecordsTable, 0) }) } func (fixture consentFixture) text(t *testing.T, purpose domain.ConsentPurpose) domain.ConsentText { t.Helper() text, err := fixture.store.ConsentTexts().Current(fixture.ctx, purpose, fixture.now) if err != nil { t.Fatalf("ConsentTexts().Current(%s) error = %v", purpose, err) } return text } func (fixture consentFixture) newGrant( t *testing.T, subject uuid.UUID, purpose domain.ConsentPurpose, version domain.ConsentTextVersion, source domain.ConsentSource, at time.Time, registrationVersions ...int64, ) domain.ConsentGrant { t.Helper() registrationVersion := int64(0) if source == domain.ConsentSourceRegistration { registrationVersion = 1 } if len(registrationVersions) > 1 { t.Fatal("newGrant received more than one registration version") } if len(registrationVersions) == 1 { registrationVersion = registrationVersions[0] } text, err := fixture.store.ConsentTexts().Get(fixture.ctx, purpose, version) if err != nil { t.Fatalf("ConsentTexts().Get(%s, %s) error = %v", purpose, version, err) } grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{ SubjectID: subject, Purpose: purpose, TextVersion: text.Version(), TextHash: text.Hash(), Source: source, RegistrationVersion: registrationVersion, GrantedAt: at, }) if err != nil { t.Fatalf("NewConsentGrant() error = %v", err) } return grant } func (fixture consentFixture) grant( t *testing.T, ledger outbound.ConsentLedger, subject uuid.UUID, purpose domain.ConsentPurpose, version domain.ConsentTextVersion, source domain.ConsentSource, at time.Time, ) domain.ConsentRecord { t.Helper() record, created, err := ledger.Grant(fixture.ctx, fixture.newGrant(t, subject, purpose, version, source, at)) if err != nil || !created { t.Fatalf("Grant(%s %s) = %v, %v, want a new record", purpose, version, created, err) } return record } // newContactGrant builds the C4 grant of an acceptance of terms version 2 // for the organization named consentOrganizationName. func (fixture consentFixture) newContactGrant( t *testing.T, subject, organization, invitation uuid.UUID, at time.Time, fields ...domain.ContactField, ) domain.ContactConsentGrant { t.Helper() return fixture.newNamedContactGrant(t, consentOrganizationName, subject, organization, invitation, at, fields...) } // newNamedContactGrant builds the C4 grant of an acceptance of terms version // 2 for the organization shown under name; the domain hashes the text as // shown. func (fixture consentFixture) newNamedContactGrant( t *testing.T, name string, subject, organization, invitation uuid.UUID, at time.Time, fields ...domain.ContactField, ) domain.ContactConsentGrant { t.Helper() set, err := domain.NewContactFieldSet(fields...) if err != nil { t.Fatalf("NewContactFieldSet() error = %v", err) } grant, err := domain.NewContactConsentGrant(domain.ContactConsentGrantInput{ SubjectID: subject, OrganizationID: organization, OrganizationName: name, Fields: set, InvitationID: invitation, InvitationTermsVersion: 2, Text: fixture.text(t, domain.ConsentPurposeContactDisclosure), GrantedAt: at, }) if err != nil { t.Fatalf("NewContactConsentGrant() error = %v", err) } return grant } func (fixture consentFixture) revoke( t *testing.T, ledger outbound.ConsentLedger, subject uuid.UUID, purpose domain.ConsentPurpose, organization uuid.UUID, at time.Time, ) []domain.ConsentRecord { t.Helper() revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ SubjectID: subject, Purpose: purpose, OrganizationID: organization, Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: at, }) if err != nil { t.Fatalf("NewConsentRevocation() error = %v", err) } revoked, err := ledger.Revoke(fixture.ctx, revocation) if err != nil { t.Fatalf("Revoke(%s) error = %v", purpose, err) } for _, record := range revoked { if record.State() != domain.ConsentStateRevoked { t.Fatalf("Revoke(%s) returned %s, want revoked records", purpose, record) } } return revoked } func (fixture consentFixture) list(t *testing.T, subject uuid.UUID, state domain.ConsentState) outbound.ConsentPage { t.Helper() page, err := fixture.store.ConsentLedger().List(fixture.ctx, outbound.ConsentListQuery{SubjectID: subject, State: state, Limit: consentPageSize}) if err != nil { t.Fatalf("List() error = %v", err) } return page } // rawRecord returns the whole stored row as JSON, so a test can prove that // a row stayed byte-for-byte the same. func (fixture consentFixture) rawRecord(t *testing.T, id uuid.UUID) string { t.Helper() var row string if err := fixture.pool.QueryRow(fixture.ctx, `SELECT row_to_json(stored)::text FROM consent_records AS stored WHERE stored.id = $1`, id).Scan(&row); err != nil { t.Fatalf("read consent record: %v", err) } return row } func assertConsentIDs(t *testing.T, records []domain.ConsentRecord, want ...uuid.UUID) { t.Helper() got := make([]uuid.UUID, 0, len(records)) for _, record := range records { got = append(got, record.ID()) } if !slices.Equal(got, want) { t.Fatalf("record IDs = %v, want %v", got, want) } } func assertConsentStates(t *testing.T, page outbound.ConsentPage, want ...domain.ConsentState) { t.Helper() got := make([]domain.ConsentState, 0, len(page.Records)) for _, record := range page.Records { got = append(got, record.State()) } if !slices.Equal(got, want) { t.Fatalf("record states = %v, want %v", got, want) } } func assertSQLError(t *testing.T, name string, err error, code, constraint string) { t.Helper() var pgError *pgconn.PgError if !errors.As(err, &pgError) || pgError.Code != code || pgError.ConstraintName != constraint { t.Fatalf("%s: error = %v, want SQLSTATE %s on %s", name, err, code, constraint) } }