feat(consent): grant consents through a version-checked usecase

This commit is contained in:
shira committed 2026-10-06 15:12:08 +03:00
1 parent de49f93b0b
commit ea0982a762
8 files changed
+1731 -11

No files matched your search

@@ -0,0 +1,556 @@
//go:build integration
package integration_test
import (
"context"
"errors"
"slices"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/consent"
)
const (
consentGrantsTestTimeout = 3 * time.Minute
// concurrentConsentRepeats repeats one grant at once, each on its own
// connection.
concurrentConsentRepeats = 8
// consentScheduledC5Version is a text that is published after the test
// clock, so it is scheduled and not yet current.
consentScheduledC5Version domain.ConsentTextVersion = "c5-2027-01-01"
)
// consentGrantsFixture runs the consent usecase on the bootstrap database.
type consentGrantsFixture struct {
ctx context.Context
pool *pgxpool.Pool
identity identityFixture
transactor *postgresadapter.Transactor
service *consent.Service
store *postgresadapter.ConsentStore
// nowNanos is the application clock, as Unix nanoseconds.
nowNanos *atomic.Int64
}
func (fixture consentGrantsFixture) now() time.Time {
return time.Unix(0, fixture.nowNanos.Load()).UTC()
}
func (fixture consentGrantsFixture) advance(by time.Duration) {
fixture.nowNanos.Store(fixture.now().Add(by).UnixNano())
}
// currentVersion returns the version of the text that is current at the
// application time.
func (fixture consentGrantsFixture) currentVersion(t *testing.T, purpose domain.ConsentPurpose) domain.ConsentTextVersion {
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.Version()
}
func (fixture consentGrantsFixture) grantInput(t *testing.T, subject uuid.UUID, purpose domain.ConsentPurpose) consent.SettingsGrantInput {
t.Helper()
return consent.SettingsGrantInput{SubjectID: subject, Purpose: purpose, TextVersion: fixture.currentVersion(t, purpose)}
}
// registerC1 records the registration C1 of an existing account in its own
// transaction.
func (fixture consentGrantsFixture) registerC1(t *testing.T, subject uuid.UUID) domain.ConsentRecord {
t.Helper()
var result consent.GrantResult
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
result, err = fixture.service.GrantAtRegistration(ctx, unit, subject, fixture.currentVersion(t, domain.ConsentPurposePersonalData))
return err
})
if err != nil || !result.Created {
t.Fatalf("GrantAtRegistration() = %v, %v, want a new record", result.Created, err)
}
return result.Record
}
// grant records a new consent in its own transaction.
func (fixture consentGrantsFixture) grant(t *testing.T, input consent.SettingsGrantInput) domain.ConsentRecord {
t.Helper()
result, err := fixture.service.GrantInSettingsInNewTransaction(fixture.ctx, input)
if err != nil || !result.Created {
t.Fatalf("GrantInSettingsInNewTransaction(%s %s) = %v, %v, want a new record", input.Purpose, input.TextVersion, result.Created, err)
}
return result.Record
}
func (fixture consentGrantsFixture) list(t *testing.T, subject uuid.UUID) outbound.ConsentPage {
t.Helper()
page, err := fixture.store.ConsentLedger().List(fixture.ctx, outbound.ConsentListQuery{SubjectID: subject, Limit: consentPageSize})
if err != nil {
t.Fatalf("List() error = %v", err)
}
return page
}
func (fixture consentGrantsFixture) revoke(t *testing.T, ledger outbound.ConsentLedger, subject uuid.UUID, purpose domain.ConsentPurpose) []domain.ConsentRecord {
t.Helper()
revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{
SubjectID: subject, Purpose: purpose, Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: fixture.now(),
})
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)
}
return revoked
}
func TestConsentGrants(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), consentGrantsTestTimeout)
defer cancel()
pool := env.newPool(ctx, t)
start := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
nowNanos := &atomic.Int64{}
nowNanos.Store(start.UnixNano())
transactor := postgresadapter.NewTransactor(pool)
fixture := consentGrantsFixture{
ctx: ctx,
pool: pool,
identity: identityFixture{
ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: start,
},
transactor: transactor,
store: postgresadapter.NewConsentStore(pool),
nowNanos: nowNanos,
}
fixture.service = consent.NewService(transactor, fixture.now)
// A second C1 text, so that the first one is outdated, and a C5 text
// that is scheduled after the test clock. Both are published the way a
// migration would publish them.
for _, text := range []struct {
purpose, version, body string
publishedAt time.Time
}{
{"c1", string(consentSecondC1Version), consentSecondC1Body, start.Add(-24 * time.Hour)},
{"c5", string(consentScheduledC5Version), "I consent to the import of my FSP results, version two.", start.Add(72 * time.Hour)},
} {
if _, err := pool.Exec(ctx, `
INSERT INTO consent_texts (purpose, version, body, body_sha256, kind, published_at)
VALUES ($1, $2, $3, sha256(convert_to($3, 'UTF8')), 'demo', $4)`,
text.purpose, text.version, text.body, text.publishedAt); err != nil {
t.Fatalf("publish the %s text %s: %v", text.purpose, text.version, err)
}
}
reset := func(t *testing.T) {
t.Helper()
fixture.nowNanos.Store(start.UnixNano())
truncateTables(ctx, t, pool, slices.Concat(identityTables, deliveryTables, consentTables)...)
}
t.Run("C1 is written in the registration transaction and the other purposes separately", func(t *testing.T) {
reset(t)
user := fixture.identity.newUser(t, "register@example.com", domain.ScenarioCandidate, start)
c1 := fixture.currentVersion(t, domain.ConsentPurposePersonalData)
// The registration has no session: the account and its C1 commit
// together on the subject ID alone.
var registered consent.GrantResult
err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := unit.Users().Create(ctx, user); err != nil {
return err
}
var err error
registered, err = fixture.service.GrantAtRegistration(ctx, unit, user.ID, c1)
return err
})
if err != nil || !registered.Created {
t.Fatalf("registration transaction = %v, %v, want an account with a new C1", registered.Created, err)
}
assertRowCount(ctx, t, pool, usersTable, 1)
assertRowCount(ctx, t, pool, sessionsTable, 0)
assertRowCount(ctx, t, pool, consentRecordsTable, 1)
if record := registered.Record; record.SubjectID() != user.ID || record.Source() != domain.ConsentSourceRegistration ||
record.TextVersion() != consentSecondC1Version || !record.GrantedAt().Equal(start) {
t.Fatalf("registration C1 = %s %s %v, want the current text at the application time", record.Source(), record.TextVersion(), record.GrantedAt())
}
// The user withholds C3 and grants C2 and C5 one by one.
fixture.advance(time.Minute)
publication := fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposePublication))
fixture.advance(time.Minute)
fsp := fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposeFSPImport))
ledger := fixture.store.ConsentLedger()
for purpose, want := range map[domain.ConsentPurpose]uuid.UUID{
domain.ConsentPurposePersonalData: registered.Record.ID(),
domain.ConsentPurposePublication: publication.ID(),
domain.ConsentPurposeFSPImport: fsp.ID(),
} {
if current, err := ledger.Current(ctx, user.ID, purpose); err != nil || current.ID() != want || current.State() != domain.ConsentStateActive {
t.Fatalf("Current(%s) = %s, %v, want its own active record", purpose, current, err)
}
}
// C3 was not given: no record, and the other purposes did not need it.
if _, err := ledger.Current(ctx, user.ID, domain.ConsentPurposeAutoCategorization); !errors.Is(err, outbound.ErrConsentNotFound) {
t.Fatalf("Current(c3) error = %v, want ErrConsentNotFound", err)
}
// Granting C3 later, then revoking it, changes no other purpose.
fixture.advance(time.Minute)
categorization := fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposeAutoCategorization))
fixture.advance(time.Minute)
if revoked := fixture.revoke(t, ledger, user.ID, domain.ConsentPurposeAutoCategorization); len(revoked) != 1 || revoked[0].ID() != categorization.ID() {
t.Fatalf("Revoke(c3) = %v, want the C3 record only", revoked)
}
page, err := ledger.List(ctx, outbound.ConsentListQuery{SubjectID: user.ID, Limit: consentPageSize})
if err != nil {
t.Fatalf("List() error = %v", err)
}
assertConsentIDs(t, page.Records, categorization.ID(), fsp.ID(), publication.ID(), registered.Record.ID())
assertConsentStates(t, page, domain.ConsentStateRevoked, domain.ConsentStateActive, domain.ConsentStateActive, domain.ConsentStateActive)
})
t.Run("a failed registration takes its C1 with it", func(t *testing.T) {
reset(t)
user := fixture.identity.newUser(t, "rollback@example.com", domain.ScenarioCandidate, start)
c1 := fixture.currentVersion(t, domain.ConsentPurposePersonalData)
err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := unit.Users().Create(ctx, user); err != nil {
return err
}
if _, err := fixture.service.GrantAtRegistration(ctx, unit, user.ID, c1); err != nil {
return err
}
return errForcedRollback
})
if !errors.Is(err, errForcedRollback) {
t.Fatalf("registration transaction error = %v, want the forced rollback", err)
}
assertRowCount(ctx, t, pool, usersTable, 0)
assertRowCount(ctx, t, pool, consentRecordsTable, 0)
// A grant for a subject that has no account is refused by the ledger
// and stores nothing.
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
_, err := fixture.service.GrantAtRegistration(ctx, unit, uuid.New(), c1)
return err
})
if !errors.Is(err, outbound.ErrUserNotFound) {
t.Fatalf("GrantAtRegistration(unknown subject) error = %v, want ErrUserNotFound", err)
}
assertRowCount(ctx, t, pool, consentRecordsTable, 0)
})
t.Run("a repeat stores nothing and an outdated version is rejected", func(t *testing.T) {
reset(t)
user := fixture.identity.createUser(t, "repeat@example.com", domain.ScenarioCandidate, start.Add(-72*time.Hour))
input := fixture.grantInput(t, user.ID, domain.ConsentPurposePublication)
first := fixture.grant(t, input)
fixture.advance(time.Hour)
repeat, err := fixture.service.GrantInSettingsInNewTransaction(ctx, input)
if err != nil || repeat.Created || repeat.Record.ID() != first.ID() || !repeat.Record.GrantedAt().Equal(start) {
t.Fatalf("GrantInSettingsInNewTransaction(repeat) = %s, %v, %v, want the first record at %v", repeat.Record, repeat.Created, err, start)
}
assertRowCount(ctx, t, pool, consentRecordsTable, 1)
// The repeat inside a business transaction does not abort it.
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
again, err := fixture.service.GrantInSettings(ctx, unit, input)
if err != nil || again.Created {
return errors.Join(err, errors.New("repeat in a transaction created a record"))
}
_, err = unit.ConsentLedger().Current(ctx, user.ID, domain.ConsentPurposePublication)
return err
})
if err != nil {
t.Fatalf("repeat in a transaction error = %v", err)
}
// C1 has a newer text: the first one is outdated. An unknown version
// and a scheduled one are not current either.
outdated := fixture.grantInput(t, user.ID, domain.ConsentPurposePersonalData)
outdated.TextVersion = "c1-2026-10-01"
scheduled := fixture.grantInput(t, user.ID, domain.ConsentPurposeFSPImport)
scheduled.TextVersion = consentScheduledC5Version
unknown := fixture.grantInput(t, user.ID, domain.ConsentPurposeAutoCategorization)
unknown.TextVersion = "c3-1999-01-01"
for name, stale := range map[string]struct {
input consent.SettingsGrantInput
current domain.ConsentTextVersion
}{
"outdated": {outdated, consentSecondC1Version},
"scheduled": {scheduled, "c5-2026-10-01"},
"unknown": {unknown, "c3-2026-10-01"},
} {
_, err := fixture.service.GrantInSettingsInNewTransaction(ctx, stale.input)
var staleError *consent.StaleConsentTextError
if !errors.Is(err, consent.ErrStaleConsentText) || !errors.As(err, &staleError) || staleError.Current != stale.current {
t.Fatalf("GrantInSettingsInNewTransaction(%s) error = %v, want a stale error naming %s", name, err, stale.current)
}
}
assertRowCount(ctx, t, pool, consentRecordsTable, 1)
// The current version of the same purpose goes through; the outdated
// text of C1 stays refused after it.
fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposePersonalData))
if _, err := fixture.service.GrantInSettingsInNewTransaction(ctx, outdated); !errors.Is(err, consent.ErrStaleConsentText) {
t.Fatalf("GrantInSettingsInNewTransaction(outdated after a current grant) error = %v, want ErrStaleConsentText", err)
}
assertRowCount(ctx, t, pool, consentRecordsTable, 2)
// A grant after a revocation is a new record, not a repeat.
fixture.advance(time.Minute)
fixture.revoke(t, fixture.store.ConsentLedger(), user.ID, domain.ConsentPurposePublication)
fixture.advance(time.Minute)
regranted := fixture.grant(t, input)
if regranted.ID() == first.ID() {
t.Fatal("a grant after a revocation reused the revoked record")
}
assertRowCount(ctx, t, pool, consentRecordsTable, 3)
})
t.Run("concurrent repeats create one record", func(t *testing.T) {
reset(t)
user := fixture.identity.createUser(t, "concurrent@example.com", domain.ScenarioCandidate, start.Add(-72*time.Hour))
input := fixture.grantInput(t, user.ID, domain.ConsentPurposePublication)
var created atomic.Int32
functions := make([]func() error, concurrentConsentRepeats)
for index := range functions {
functions[index] = func() error {
result, err := fixture.service.GrantInSettingsInNewTransaction(ctx, input)
if err == nil && result.Created {
created.Add(1)
}
return err
}
}
for index, err := range runAtOnce(functions...) {
if err != nil {
t.Fatalf("concurrent grant %d error = %v", index, err)
}
}
if created.Load() != 1 {
t.Fatalf("%d concurrent grants created a record, want 1", created.Load())
}
assertRowCount(ctx, t, pool, consentRecordsTable, 1)
})
t.Run("a repeat of an outdated version after a new publication is stale", func(t *testing.T) {
reset(t)
user := fixture.identity.createUser(t, "republished@example.com", domain.ScenarioCandidate, start.Add(-72*time.Hour))
input := fixture.grantInput(t, user.ID, domain.ConsentPurposeAutoCategorization)
first := fixture.grant(t, input)
// Version two of C3 is published the way a migration would, after
// version one was granted and before the repeat.
const secondC3Version = "c3-2026-10-05"
if _, err := pool.Exec(ctx, `
INSERT INTO consent_texts (purpose, version, body, body_sha256, kind, published_at)
VALUES ('c3', $1, $2, sha256(convert_to($2, 'UTF8')), 'demo', $3)`,
secondC3Version, "I consent to the automatic categorization, version two.", start.Add(-time.Hour)); err != nil {
t.Fatalf("publish the second C3 text: %v", err)
}
_, err := fixture.service.GrantInSettingsInNewTransaction(ctx, input)
var stale *consent.StaleConsentTextError
if !errors.Is(err, consent.ErrStaleConsentText) || !errors.As(err, &stale) || stale.Current != secondC3Version {
t.Fatalf("repeat of version one error = %v, want a stale error naming %s", err, secondC3Version)
}
assertRowCount(ctx, t, pool, consentRecordsTable, 1)
if current, err := fixture.store.ConsentLedger().Current(ctx, user.ID, domain.ConsentPurposeAutoCategorization); err != nil || current.ID() != first.ID() {
t.Fatalf("Current(c3) = %s, %v, want the first record", current, err)
}
})
t.Run("a re-registration records its C1 after UpdateRegistration", func(t *testing.T) {
reset(t)
reregister := func(t *testing.T, rawEmail string, grantFirst bool) (granted consent.GrantResult, earlier domain.ConsentRecord) {
t.Helper()
first := fixture.identity.createUser(t, rawEmail, domain.ScenarioCandidate, start.Add(-72*time.Hour))
earlier = fixture.registerC1(t, first.ID)
changed, err := first.ReRegister(fixture.identity.registration(t, rawEmail, domain.ScenarioEmployer, start))
if err != nil {
t.Fatalf("ReRegister() error = %v", err)
}
version := fixture.currentVersion(t, domain.ConsentPurposePersonalData)
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
grant := func() error {
var err error
granted, err = fixture.service.GrantAtRegistration(ctx, unit, first.ID, version)
return err
}
if grantFirst {
if err := grant(); err != nil {
return err
}
}
if _, err := unit.Users().UpdateRegistration(ctx, changed); err != nil {
return err
}
if grantFirst {
return nil
}
return grant()
})
if err != nil {
t.Fatalf("re-registration transaction error = %v", err)
}
return granted, earlier
}
// Correct order: UpdateRegistration deletes the earlier registrant's
// C1, then the grant creates the new one.
granted, earlier := reregister(t, "after@example.com", false)
if !granted.Created || granted.Record.ID() == earlier.ID() {
t.Fatalf("GrantAtRegistration after UpdateRegistration = %s, created %v, want a new record", granted.Record, granted.Created)
}
assertConsentIDs(t, fixture.list(t, granted.Record.SubjectID()).Records, granted.Record.ID())
// The hazard: a grant before UpdateRegistration finds the earlier
// C1 and reports Created false, and the update then deletes it, so
// the account is left without any C1.
before, earlierBefore := reregister(t, "before@example.com", true)
if before.Created || before.Record.ID() != earlierBefore.ID() {
t.Fatalf("GrantAtRegistration before UpdateRegistration = %s, created %v, want the earlier record", before.Record, before.Created)
}
if page := fixture.list(t, before.Record.SubjectID()); len(page.Records) != 0 {
t.Fatalf("a grant before UpdateRegistration left %d records, want none: the earlier C1 is deleted", len(page.Records))
}
})
t.Run("C4 is granted only through its scoped operation", func(t *testing.T) {
reset(t)
user := fixture.identity.createUser(t, "contact@example.com", domain.ScenarioCandidate, start.Add(-72*time.Hour))
generic := fixture.grantInput(t, user.ID, domain.ConsentPurposeContactDisclosure)
_, err := fixture.service.GrantInSettingsInNewTransaction(ctx, generic)
if !errors.Is(err, consent.ErrScopedConsentRequired) {
t.Fatalf("GrantInSettingsInNewTransaction(C4) error = %v, want ErrScopedConsentRequired", err)
}
assertRowCount(ctx, t, pool, consentRecordsTable, 0)
fields, err := domain.NewContactFieldSet(domain.ContactFieldEmail)
if err != nil {
t.Fatalf("NewContactFieldSet() error = %v", err)
}
organization, invitation := uuid.New(), uuid.New()
contact := consent.ContactGrantInput{
SubjectID: user.ID, OrganizationID: organization, OrganizationName: consentOrganizationName, Fields: fields,
InvitationID: invitation, InvitationTermsVersion: 2, TextVersion: generic.TextVersion,
}
var granted consent.GrantResult
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
granted, err = fixture.service.GrantContact(ctx, unit, contact)
return err
})
if err != nil || !granted.Created {
t.Fatalf("GrantContact() = %v, %v, want a new record", granted.Created, err)
}
record := granted.Record
if record.Purpose() != domain.ConsentPurposeContactDisclosure || record.Source() != domain.ConsentSourceInvitationAcceptance ||
record.OrganizationID() != organization || record.OrganizationName() != consentOrganizationName ||
!record.Fields().Equal(fields) || record.InvitationID() != invitation || !record.GrantedAt().Equal(start) {
t.Fatalf("GrantContact() record = %s, want the scope of its input at the application time", record)
}
// A repeat returns the record; an outdated C4 text is refused.
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
repeat, err := fixture.service.GrantContact(ctx, unit, contact)
if err == nil && (repeat.Created || repeat.Record.ID() != record.ID()) {
err = errors.New("repeat did not return the existing record")
}
return err
})
if err != nil {
t.Fatalf("GrantContact(repeat) error = %v", err)
}
outdated := contact
outdated.InvitationID, outdated.TextVersion = uuid.New(), "c4-1999-01-01"
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
_, err := fixture.service.GrantContact(ctx, unit, outdated)
return err
})
if !errors.Is(err, consent.ErrStaleConsentText) {
t.Fatalf("GrantContact(outdated) error = %v, want ErrStaleConsentText", err)
}
assertRowCount(ctx, t, pool, consentRecordsTable, 1)
// C4 gives no other purpose.
if _, err := fixture.store.ConsentLedger().Current(ctx, user.ID, domain.ConsentPurposePublication); !errors.Is(err, outbound.ErrConsentNotFound) {
t.Fatalf("Current(c2) after C4 error = %v, want ErrConsentNotFound", err)
}
})
// This subtest must stay last: it closes the shared pool to simulate a
// restart, so no later subtest could use the fixture.
t.Run("a new repository instance reads the history with its revocations", func(t *testing.T) {
reset(t)
user := fixture.identity.createUser(t, "restart@example.com", domain.ScenarioCandidate, start.Add(-72*time.Hour))
grantedAt := map[uuid.UUID]time.Time{}
c1 := fixture.registerC1(t, user.ID)
grantedAt[c1.ID()] = fixture.now()
fixture.advance(time.Minute)
c2 := fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposePublication))
grantedAt[c2.ID()] = fixture.now()
fixture.advance(time.Minute)
c5 := fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposeFSPImport))
grantedAt[c5.ID()] = fixture.now()
fixture.advance(time.Minute)
revokedAt := fixture.now()
if revoked := fixture.revoke(t, fixture.store.ConsentLedger(), user.ID, domain.ConsentPurposePublication); len(revoked) != 1 {
t.Fatalf("Revoke(c2) = %v, want one record", revoked)
}
fixture.advance(time.Minute)
c2Again := fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposePublication))
grantedAt[c2Again.ID()] = fixture.now()
// Restart: close the pool and build every repository and the usecase
// again from a new one.
pool.Close()
restartedPool := env.newPool(ctx, t)
restartedStore := postgresadapter.NewConsentStore(restartedPool)
restartedService := consent.NewService(postgresadapter.NewTransactor(restartedPool), fixture.now)
page, err := restartedStore.ConsentLedger().List(ctx, outbound.ConsentListQuery{SubjectID: user.ID, Limit: consentPageSize})
if err != nil {
t.Fatalf("List() after restart error = %v", err)
}
assertConsentIDs(t, page.Records, c2Again.ID(), c5.ID(), c2.ID(), c1.ID())
assertConsentStates(t, page, domain.ConsentStateActive, domain.ConsentStateActive, domain.ConsentStateRevoked, domain.ConsentStateActive)
revokedRecord := page.Records[2]
if stamped, ok := revokedRecord.RevokedAt(); !ok || !stamped.Equal(revokedAt) ||
revokedRecord.RevocationSource() != domain.ConsentRevocationSourceConsentSettings {
t.Fatalf("revoked record = %v %v %q, want the stamp %v", stamped, ok, revokedRecord.RevocationSource(), revokedAt)
}
for _, record := range page.Records {
if want := grantedAt[record.ID()]; !record.GrantedAt().Equal(want) {
t.Fatalf("record %s granted at %v, want the application time %v", record, record.GrantedAt(), want)
}
}
// The restarted instance sees the same state: a repeat stores nothing.
current, err := restartedStore.ConsentTexts().Current(ctx, domain.ConsentPurposePublication, fixture.now())
if err != nil {
t.Fatalf("ConsentTexts().Current(c2) after restart error = %v", err)
}
repeat, err := restartedService.GrantInSettingsInNewTransaction(ctx, consent.SettingsGrantInput{
SubjectID: user.ID, Purpose: domain.ConsentPurposePublication, TextVersion: current.Version(),
})
if err != nil || repeat.Created || repeat.Record.ID() != c2Again.ID() {
t.Fatalf("GrantInSettingsInNewTransaction(repeat after restart) = %s, %v, %v, want the existing record", repeat.Record, repeat.Created, err)
}
assertRowCount(ctx, t, restartedPool, consentRecordsTable, 4)
})
}
+10 -3
View File
@@ -80,9 +80,16 @@ type ConsentLedger interface {
// A grant of another version is a new record next to the earlier one.
// Superseded is decided by granted_at, then the record ID: the
// unrevoked record granted last is active, whatever its text version,
// so Grant accepts any published version. The grant usecase (TASK-063)
// must check that the version is the current text of the purpose,
// ConsentTexts().Current at the grant time, before it calls Grant.
// so Grant accepts any published version. The usecase consent.Service
// (TASK-063) is the path that checks that the version is the current
// text of the purpose, ConsentTexts().Current at the grant time, before
// it calls Grant; business code grants through it, not directly.
//
// A subject may leave any purpose ungranted: the ledger has no rule that
// ties one purpose to another, and a subject without C3 has no C3 record,
// so Current returns ErrConsentNotFound. That is not an error state of
// the account. No caller may treat a missing C3 as a reason to refuse the
// profile or the manual assessment path.
Grant(ctx context.Context, grant domain.ConsentGrant) (record domain.ConsentRecord, created bool, err error)
// GrantContact records the C4 grant of an invitation acceptance with its
+376
View File
@@ -0,0 +1,376 @@
// Package consent grants the consents C1-C5 of the consent ledger.
//
// A grant is checked against the current published text of its purpose and
// is recorded with the application clock; the client names the text version
// it showed, never the time. The purposes are independent: no grant here
// requires, implies, or changes another one. In particular C3 is optional.
// Nothing in this package, and no gate that is built on it, may require an
// active C3 for the profile, the manual assessment path, or any other
// product function; a subject without C3 simply has no C3 record, and
// Current reports ErrConsentNotFound for it.
//
// Revocation is not part of this package. Its downstream effects (closing
// publication and grants, the deletion request, the manual path, stopping
// the import) belong to TASK-064, which calls ConsentLedger().Revoke.
package consent
import (
"context"
"errors"
"fmt"
"math/rand/v2"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// maxTransactionAttempts bounds the retries of GrantInNewTransaction after a
// transaction conflict. A repeated grant is idempotent, so a retry is safe.
const maxTransactionAttempts = 3
// retryBackoff is the base wait between the attempts of
// GrantInSettingsInNewTransaction. Each wait adds a random part of up to the
// same length, so concurrent callers that conflicted do not retry in step.
const retryBackoff = 10 * time.Millisecond
var (
// ErrStaleConsentText reports a grant of a text version that is not the
// current published text of the purpose: an older version, a version that
// is scheduled but not yet published, or one that does not exist. Nothing
// was stored. errors.As with *StaleConsentTextError yields the current
// version, so a client can show the new text and ask again.
ErrStaleConsentText = errors.New("consent text version is not current")
// ErrScopedConsentRequired reports a grant of C4 through the generic
// path. C4 is granted only by GrantContact, with its organization,
// fields, and invitation.
ErrScopedConsentRequired = errors.New("consent purpose requires its scope")
)
// StaleConsentTextError carries the versions of a stale grant. It matches
// ErrStaleConsentText with errors.Is.
type StaleConsentTextError struct {
Purpose domain.ConsentPurpose
Requested domain.ConsentTextVersion
Current domain.ConsentTextVersion
}
func (err *StaleConsentTextError) Error() string {
return fmt.Sprintf("consent text version is not current: purpose %s, requested %s, current %s", err.Purpose, err.Requested, err.Current)
}
func (err *StaleConsentTextError) Unwrap() error { return ErrStaleConsentText }
// Service grants consents. It holds no state; the same instance serves
// concurrent callers.
type Service struct {
transactor outbound.Transactor
clock func() time.Time
}
// NewService takes the application clock, which is the only source of the
// grant time, and the transactor that GrantInSettingsInNewTransaction uses.
// A nil transactor or clock is a wiring mistake and panics at construction,
// not at the first grant.
func NewService(transactor outbound.Transactor, clock func() time.Time) *Service {
if transactor == nil {
panic("consent.NewService - transactor must not be nil")
}
if clock == nil {
panic("consent.NewService - clock must not be nil")
}
return &Service{transactor: transactor, clock: clock}
}
// GrantResult is the outcome of a grant. Created is false when the subject
// already had an unrevoked record of the purpose and version; Record is then
// that record and nothing was stored.
type GrantResult struct {
Record domain.ConsentRecord
Created bool
}
// SettingsGrantInput describes a grant of C1, C2, C3, or C5 in the consent
// settings. There is no time field: the service stamps the grant with its
// clock. There is no source field either: the entry points fix it, so a
// handler cannot take it from the client.
type SettingsGrantInput struct {
SubjectID uuid.UUID
Purpose domain.ConsentPurpose
// TextVersion is the version of the text the subject was shown.
TextVersion domain.ConsentTextVersion
}
// CheckTextVersion reports whether version is the current published text of
// the purpose at the application time, and returns that text. It grants
// nothing and writes nothing. Any other version fails with
// *StaleConsentTextError: an older one, one that is scheduled but not yet
// published, and one that never existed.
//
// The registration (TASK-053) must call it with C1 and the submitted version
// before it branches on a new or an existing email. A stale version then
// fails the same way for both, so the answer does not reveal whether the
// account exists; GrantAtRegistration repeats the check inside the
// transaction, where the answer is final.
func (service *Service) CheckTextVersion(
ctx context.Context,
repositories outbound.ConsentRepositories,
purpose domain.ConsentPurpose,
version domain.ConsentTextVersion,
) (domain.ConsentText, error) {
const location = "Service.CheckTextVersion"
if _, err := domain.ParseConsentPurpose(string(purpose)); err != nil {
return domain.ConsentText{}, fmt.Errorf("%s - validate purpose: %w", location, err)
}
if _, err := domain.ParseConsentTextVersion(string(version)); err != nil {
return domain.ConsentText{}, fmt.Errorf("%s - validate text version: %w", location, err)
}
text, err := currentText(ctx, repositories, purpose, version, service.clock())
if err != nil {
return domain.ConsentText{}, fmt.Errorf("%s - check text version: %w", location, err)
}
return text, nil
}
// GrantAtRegistration records the C1 of a registration, with the source
// ConsentSourceRegistration, in the repositories of the caller. Pass the
// UnitOfWork of the registration transaction: the account and its C1 commit
// together on the subject ID alone, before any session exists.
//
// For the re-registration of an unverified account, call it strictly after
// UserRepository.UpdateRegistration in the same transaction. UpdateRegistration
// deletes the registration C1 of the earlier registrant, and a repeat grant
// that ran before it would find that record, return it with Created false,
// and leave the account without any C1 once it is deleted.
//
// It checks the text version like CheckTextVersion does, and the rules of
// grant apply: server time, one record per subject and version, and an
// idempotent repeat.
func (service *Service) GrantAtRegistration(
ctx context.Context,
repositories outbound.ConsentRepositories,
subjectID uuid.UUID,
version domain.ConsentTextVersion,
) (GrantResult, error) {
result, err := service.grant(ctx, repositories, grantRequest{
subjectID: subjectID,
purpose: domain.ConsentPurposePersonalData,
version: version,
source: domain.ConsentSourceRegistration,
})
if err != nil {
return GrantResult{}, fmt.Errorf("Service.GrantAtRegistration - %w", err)
}
return result, nil
}
// GrantInSettings records a grant of C1, C2, C3, or C5 given in the consent
// settings, with the source ConsentSourceConsentSettings, in the repositories
// of the caller. Pass the UnitOfWork of a business transaction to make the
// grant atomic with it; use GrantInSettingsInNewTransaction for a grant that
// stands alone.
//
// It reads the current text of the purpose at the application clock time and
// refuses any other version with *StaleConsentTextError. The ledger accepts
// any published version, so this check is what keeps a grant from recording
// an outdated text. A text published between the check and the insert is not
// a problem: the grant was valid at the time it was checked. A repeat that
// names an older version after a newer text was published is stale, not a
// repeat: the subject has to see the new text.
//
// A repeat of the same subject, purpose, and current version returns the
// existing record with Created false. The repeat keeps the first grant time
// and does not abort a surrounding transaction. A failure of the ledger (an
// unknown subject, ErrConsentTextNotFound when the purpose has no published
// text) returns with its sentinel and, as a database error, aborts the
// transaction, so the caller must return it.
//
// outbound.ErrTransactionConflict is the exception: the ledger returns it
// without aborting the transaction when the record of a repeat was revoked
// between its two statements. A caller inside a UnitOfWork must return it,
// roll the transaction back, and retry the whole operation; the retry
// inserts a new record.
//
// C4 is refused with ErrScopedConsentRequired before anything is read: it is
// granted only with GrantContact.
func (service *Service) GrantInSettings(
ctx context.Context,
repositories outbound.ConsentRepositories,
input SettingsGrantInput,
) (GrantResult, error) {
result, err := service.grant(ctx, repositories, grantRequest{
subjectID: input.SubjectID,
purpose: input.Purpose,
version: input.TextVersion,
source: domain.ConsentSourceConsentSettings,
})
if err != nil {
return GrantResult{}, fmt.Errorf("Service.GrantInSettings - %w", err)
}
return result, nil
}
// GrantInSettingsInNewTransaction runs GrantInSettings in its own
// transaction, for a grant that is not part of another business operation. A
// transaction conflict, which includes a repeat whose existing record was
// revoked concurrently, is retried up to maxTransactionAttempts times in
// total with a short jittered wait between the attempts; the retry is
// idempotent. Called with the context of a Transactor callback it fails with
// outbound.ErrNestedTransaction.
func (service *Service) GrantInSettingsInNewTransaction(ctx context.Context, input SettingsGrantInput) (GrantResult, error) {
var result GrantResult
err := service.inNewTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
granted, err := service.GrantInSettings(ctx, unit, input)
result = granted
return err
})
if err != nil {
return GrantResult{}, fmt.Errorf("Service.GrantInSettingsInNewTransaction - run transaction: %w", err)
}
return result, nil
}
// grantRequest is a grant of C1, C2, C3, or C5 with its source, which the
// public entry points fix.
type grantRequest struct {
subjectID uuid.UUID
purpose domain.ConsentPurpose
version domain.ConsentTextVersion
source domain.ConsentSource
}
func (service *Service) grant(ctx context.Context, repositories outbound.ConsentRepositories, request grantRequest) (GrantResult, error) {
if _, err := domain.ParseConsentPurpose(string(request.purpose)); err != nil {
return GrantResult{}, fmt.Errorf("validate purpose: %w", err)
}
if request.purpose.OrganizationScoped() {
return GrantResult{}, fmt.Errorf("%s is granted with GrantContact: %w", request.purpose, ErrScopedConsentRequired)
}
if _, err := domain.ParseConsentTextVersion(string(request.version)); err != nil {
return GrantResult{}, fmt.Errorf("validate text version: %w", err)
}
// One reading serves the check and the grant time.
now := service.clock()
text, err := currentText(ctx, repositories, request.purpose, request.version, now)
if err != nil {
return GrantResult{}, fmt.Errorf("check text version: %w", err)
}
grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{
SubjectID: request.subjectID,
Purpose: request.purpose,
TextVersion: text.Version(),
TextHash: text.Hash(),
Source: request.source,
GrantedAt: now,
})
if err != nil {
return GrantResult{}, fmt.Errorf("build grant: %w", err)
}
record, created, err := repositories.ConsentLedger().Grant(ctx, grant)
if err != nil {
return GrantResult{}, fmt.Errorf("record grant: %w", err)
}
return GrantResult{Record: record, Created: created}, nil
}
// ContactGrantInput describes the C4 grant of an invitation acceptance. The
// organization name is the name the candidate was shown; the ledger stores it
// as the snapshot that proves the text. The caller takes every value from
// the invitation it has just checked, never from the request alone.
type ContactGrantInput struct {
SubjectID uuid.UUID
OrganizationID uuid.UUID
OrganizationName string
Fields domain.ContactFieldSet
InvitationID uuid.UUID
InvitationTermsVersion int64
// TextVersion is the version of the C4 text the subject was shown.
TextVersion domain.ConsentTextVersion
}
// GrantContact records the C4 grant of an invitation acceptance. It is the
// only way to grant C4: it is scoped to one organization, the fields, and the
// invitation, and it has the source ConsentSourceInvitationAcceptance, so a
// generic Grant cannot produce it and no registration or consent-settings
// flow includes it.
//
// It checks that TextVersion is the current C4 text like GrantInSettings does, and
// the ledger checks that the hash is the hash of that text with the
// organization name filled in. It is meant for the transaction of the
// acceptance (TASK-201), next to the invitation state change and the audit
// event. When the invitation already has a C4 record of the same subject,
// the result has Created false and holds that record, revoked or not; the
// caller compares its scope with the input to tell a repeat from a conflict.
// A record that belongs to another subject returns
// outbound.ErrConsentInvitationTaken.
//
// The text check comes first, so a repeat that arrives after a newer C4 text
// was published fails as stale. A caller that wants to answer a repeat with
// the earlier result must look for the existing record before it calls.
func (service *Service) GrantContact(ctx context.Context, repositories outbound.ConsentRepositories, input ContactGrantInput) (GrantResult, error) {
const location = "Service.GrantContact"
if _, err := domain.ParseConsentTextVersion(string(input.TextVersion)); err != nil {
return GrantResult{}, fmt.Errorf("%s - validate text version: %w", location, err)
}
now := service.clock()
text, err := currentText(ctx, repositories, domain.ConsentPurposeContactDisclosure, input.TextVersion, now)
if err != nil {
return GrantResult{}, fmt.Errorf("%s - check text version: %w", location, err)
}
grant, err := domain.NewContactConsentGrant(domain.ContactConsentGrantInput{
SubjectID: input.SubjectID,
OrganizationID: input.OrganizationID,
OrganizationName: input.OrganizationName,
Fields: input.Fields,
InvitationID: input.InvitationID,
InvitationTermsVersion: input.InvitationTermsVersion,
Text: text,
GrantedAt: now,
})
if err != nil {
return GrantResult{}, fmt.Errorf("%s - build grant: %w", location, err)
}
record, created, err := repositories.ConsentLedger().GrantContact(ctx, grant)
if err != nil {
return GrantResult{}, fmt.Errorf("%s - record grant: %w", location, err)
}
return GrantResult{Record: record, Created: created}, nil
}
// currentText returns the current text of the purpose at now when its version
// is the requested one, and *StaleConsentTextError otherwise.
func currentText(
ctx context.Context,
repositories outbound.ConsentRepositories,
purpose domain.ConsentPurpose,
requested domain.ConsentTextVersion,
now time.Time,
) (domain.ConsentText, error) {
text, err := repositories.ConsentTexts().Current(ctx, purpose, now)
if err != nil {
return domain.ConsentText{}, fmt.Errorf("read current text of %s: %w", purpose, err)
}
if text.Version() != requested {
return domain.ConsentText{}, &StaleConsentTextError{Purpose: purpose, Requested: requested, Current: text.Version()}
}
return text, nil
}
func (service *Service) inNewTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error {
for attempt := 1; ; attempt++ {
err := service.transactor.WithinTransaction(ctx, work)
if err == nil || !errors.Is(err, outbound.ErrTransactionConflict) || attempt >= maxTransactionAttempts || ctx.Err() != nil {
return err
}
timer := time.NewTimer(retryBackoff + rand.N(retryBackoff)) //nolint:gosec // jitter only, not a security value
select {
case <-ctx.Done():
timer.Stop()
return err
case <-timer.C:
}
}
}
@@ -0,0 +1,725 @@
package consent_test
import (
"context"
"errors"
"slices"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/consent"
)
const (
organizationName = "Acme Synthetic LLC"
termsVersion = 2
)
var (
// published is the publication time of the first text of every purpose.
published = time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
// clockStart is after every published text and before the scheduled one.
clockStart = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
allPurposes = []domain.ConsentPurpose{
domain.ConsentPurposePersonalData,
domain.ConsentPurposePublication,
domain.ConsentPurposeAutoCategorization,
domain.ConsentPurposeContactDisclosure,
domain.ConsentPurposeFSPImport,
}
)
func TestGrantRecordsCurrentVersionWithServerTime(t *testing.T) {
harness := newHarness(t)
subject := uuid.New()
for index, purpose := range []domain.ConsentPurpose{
domain.ConsentPurposePersonalData,
domain.ConsentPurposePublication,
domain.ConsentPurposeAutoCategorization,
domain.ConsentPurposeFSPImport,
} {
wantTime := harness.clock.now
source := domain.ConsentSourceConsentSettings
result, err := harness.service.GrantInSettings(t.Context(), harness.repositories, consent.SettingsGrantInput{
SubjectID: subject, Purpose: purpose, TextVersion: harness.version(purpose),
})
if err != nil || !result.Created {
t.Fatalf("Grant(%s) = %v, %v, want a new record", purpose, result.Created, err)
}
record := result.Record
text := harness.current(purpose)
if !record.GrantedAt().Equal(wantTime) {
t.Errorf("Grant(%s) granted at %v, want the application clock %v", purpose, record.GrantedAt(), wantTime)
}
if record.TextVersion() != text.Version() || record.TextHash() != text.Hash() || record.Source() != source ||
record.SubjectID() != subject || record.Purpose() != purpose {
t.Errorf("Grant(%s) record = %s %s, want the current text bound to the subject", purpose, record.TextVersion(), record.Source())
}
if got := len(harness.ledger.records); got != index+1 {
t.Errorf("ledger has %d records after %d grants", got, index+1)
}
harness.clock.advance(time.Minute)
}
}
func TestGrantAtRegistrationRecordsC1WithTheRegistrationSource(t *testing.T) {
harness := newHarness(t)
subject := uuid.New()
result, err := harness.service.GrantAtRegistration(t.Context(), harness.repositories, subject, harness.version(domain.ConsentPurposePersonalData))
if err != nil || !result.Created {
t.Fatalf("GrantAtRegistration() = %v, %v, want a new record", result.Created, err)
}
record := result.Record
if record.Purpose() != domain.ConsentPurposePersonalData || record.Source() != domain.ConsentSourceRegistration ||
record.SubjectID() != subject || !record.GrantedAt().Equal(clockStart) {
t.Fatalf("GrantAtRegistration() record = %s %s, want the registration C1 at the application clock", record.Purpose(), record.Source())
}
_, err = harness.service.GrantAtRegistration(t.Context(), harness.repositories, subject, "c1-1999-01-01")
if !errors.Is(err, consent.ErrStaleConsentText) {
t.Fatalf("GrantAtRegistration(outdated) error = %v, want ErrStaleConsentText", err)
}
if len(harness.ledger.records) != 1 {
t.Fatalf("ledger has %d records, want only the first C1", len(harness.ledger.records))
}
}
// TestCheckTextVersionGrantsNothing covers the check that the registration
// runs before it branches on a new or an existing email.
func TestCheckTextVersionGrantsNothing(t *testing.T) {
harness := newHarness(t)
harness.publish(domain.ConsentPurposePersonalData, "c1-2026-10-05", published.Add(24*time.Hour))
harness.publish(domain.ConsentPurposePersonalData, "c1-2026-12-01", clockStart.Add(72*time.Hour))
text, err := harness.service.CheckTextVersion(t.Context(), harness.repositories, domain.ConsentPurposePersonalData, "c1-2026-10-05")
if err != nil || text.Version() != "c1-2026-10-05" || text.Hash() != harness.current(domain.ConsentPurposePersonalData).Hash() {
t.Fatalf("CheckTextVersion(current) = %s, %v, want the current text", text.Version(), err)
}
contact, err := harness.service.CheckTextVersion(t.Context(), harness.repositories, domain.ConsentPurposeContactDisclosure, harness.version(domain.ConsentPurposeContactDisclosure))
if err != nil || contact.Purpose() != domain.ConsentPurposeContactDisclosure {
t.Fatalf("CheckTextVersion(C4) = %v, %v, want the C4 text", contact.Purpose(), err)
}
for name, requested := range map[string]domain.ConsentTextVersion{
"an older version": "c1-2026-10-01",
"an unknown version": "c1-1999-01-01",
"a scheduled text": "c1-2026-12-01",
} {
t.Run(name, func(t *testing.T) {
_, err := harness.service.CheckTextVersion(t.Context(), harness.repositories, domain.ConsentPurposePersonalData, requested)
var stale *consent.StaleConsentTextError
if !errors.Is(err, consent.ErrStaleConsentText) || !errors.As(err, &stale) || stale.Current != "c1-2026-10-05" {
t.Fatalf("CheckTextVersion() error = %v, want a stale error naming c1-2026-10-05", err)
}
})
}
if _, err := harness.service.CheckTextVersion(t.Context(), harness.repositories, "c9", "c9-1"); !errors.Is(err, domain.ErrInvalidConsent) {
t.Fatalf("CheckTextVersion(unknown purpose) error = %v, want ErrInvalidConsent", err)
}
if _, err := harness.service.CheckTextVersion(t.Context(), harness.repositories, domain.ConsentPurposePersonalData, "c1 bad"); !errors.Is(err, domain.ErrInvalidConsentText) {
t.Fatalf("CheckTextVersion(malformed version) error = %v, want ErrInvalidConsentText", err)
}
if harness.ledger.grantCalls != 0 || len(harness.ledger.records) != 0 {
t.Fatalf("CheckTextVersion reached the ledger")
}
}
func TestGrantRejectsAStaleVersion(t *testing.T) {
harness := newHarness(t)
harness.publish(domain.ConsentPurposePersonalData, "c1-2026-10-05", published.Add(24*time.Hour))
harness.publish(domain.ConsentPurposePersonalData, "c1-2026-12-01", clockStart.Add(72*time.Hour))
subject := uuid.New()
for name, requested := range map[string]domain.ConsentTextVersion{
"an older version": "c1-2026-10-01",
"an unknown version": "c1-1999-01-01",
"a scheduled text": "c1-2026-12-01",
} {
t.Run(name, func(t *testing.T) {
_, err := harness.service.GrantInSettings(t.Context(), harness.repositories, consent.SettingsGrantInput{
SubjectID: subject, Purpose: domain.ConsentPurposePersonalData, TextVersion: requested,
})
if !errors.Is(err, consent.ErrStaleConsentText) {
t.Fatalf("Grant() error = %v, want ErrStaleConsentText", err)
}
var stale *consent.StaleConsentTextError
if !errors.As(err, &stale) || stale.Current != "c1-2026-10-05" || stale.Requested != requested || stale.Purpose != domain.ConsentPurposePersonalData {
t.Fatalf("Grant() stale error = %+v, want the current version c1-2026-10-05", stale)
}
if len(harness.ledger.records) != 0 || harness.ledger.grantCalls != 0 {
t.Fatalf("a stale grant reached the ledger: %d records, %d calls", len(harness.ledger.records), harness.ledger.grantCalls)
}
})
}
}
func TestGrantRefusesWhatItCannotRecord(t *testing.T) {
harness := newHarness(t)
valid := consent.SettingsGrantInput{
SubjectID: uuid.New(), Purpose: domain.ConsentPurposePublication,
TextVersion: harness.version(domain.ConsentPurposePublication),
}
tests := []struct {
name string
change func(*consent.SettingsGrantInput)
want error
}{
{"C4 on the generic path", func(in *consent.SettingsGrantInput) {
in.Purpose, in.TextVersion = domain.ConsentPurposeContactDisclosure, harness.version(domain.ConsentPurposeContactDisclosure)
}, consent.ErrScopedConsentRequired},
{"an unknown purpose", func(in *consent.SettingsGrantInput) { in.Purpose = "c9" }, domain.ErrInvalidConsent},
{"a malformed version", func(in *consent.SettingsGrantInput) { in.TextVersion = "c2 2026" }, domain.ErrInvalidConsentText},
{"an empty version", func(in *consent.SettingsGrantInput) { in.TextVersion = "" }, domain.ErrInvalidConsentText},
{"a nil subject", func(in *consent.SettingsGrantInput) { in.SubjectID = uuid.Nil }, domain.ErrInvalidConsent},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
input := valid
test.change(&input)
_, err := harness.service.GrantInSettings(t.Context(), harness.repositories, input)
if !errors.Is(err, test.want) {
t.Fatalf("Grant() error = %v, want %v", err, test.want)
}
if harness.ledger.grantCalls != 0 || len(harness.ledger.records) != 0 {
t.Fatalf("a refused grant reached the ledger")
}
})
}
}
func TestGrantRefusesC4WithoutReadingTheLedger(t *testing.T) {
harness := newHarness(t)
input := consent.SettingsGrantInput{
SubjectID: uuid.New(), Purpose: domain.ConsentPurposeContactDisclosure,
TextVersion: harness.version(domain.ConsentPurposeContactDisclosure),
}
// Reading the version for the input is the test's own text read.
harness.texts.reads = 0
_, err := harness.service.GrantInSettings(t.Context(), harness.repositories, input)
if !errors.Is(err, consent.ErrScopedConsentRequired) {
t.Fatalf("Grant(C4) error = %v, want ErrScopedConsentRequired", err)
}
if harness.texts.reads != 0 || harness.ledger.grantCalls != 0 {
t.Fatalf("Grant(C4) touched the repositories: %d text reads, %d ledger calls", harness.texts.reads, harness.ledger.grantCalls)
}
}
func TestGrantRepeatDoesNotDuplicateTheAction(t *testing.T) {
harness := newHarness(t)
input := consent.SettingsGrantInput{
SubjectID: uuid.New(), Purpose: domain.ConsentPurposePublication,
TextVersion: harness.version(domain.ConsentPurposePublication),
}
first, err := harness.service.GrantInSettings(t.Context(), harness.repositories, input)
if err != nil || !first.Created {
t.Fatalf("Grant() = %v, %v, want a new record", first.Created, err)
}
harness.clock.advance(time.Hour)
repeat, err := harness.service.GrantInSettings(t.Context(), harness.repositories, input)
if err != nil || repeat.Created {
t.Fatalf("Grant(repeat) = %v, %v, want the existing record", repeat.Created, err)
}
if repeat.Record.ID() != first.Record.ID() || !repeat.Record.GrantedAt().Equal(clockStart) {
t.Fatalf("Grant(repeat) record = %s at %v, want the first grant at %v", repeat.Record.ID(), repeat.Record.GrantedAt(), clockStart)
}
if len(harness.ledger.records) != 1 {
t.Fatalf("ledger has %d records after a repeat, want 1", len(harness.ledger.records))
}
}
// TestRepeatOfAnOutdatedVersionIsStale grants version one, publishes version
// two, and repeats version one: the repeat is not idempotent success but a
// stale version, and the ledger keeps its one record.
func TestRepeatOfAnOutdatedVersionIsStale(t *testing.T) {
harness := newHarness(t)
input := consent.SettingsGrantInput{
SubjectID: uuid.New(), Purpose: domain.ConsentPurposePublication,
TextVersion: harness.version(domain.ConsentPurposePublication),
}
first, err := harness.service.GrantInSettings(t.Context(), harness.repositories, input)
if err != nil || !first.Created {
t.Fatalf("GrantInSettings(v1) = %v, %v, want a new record", first.Created, err)
}
harness.publish(domain.ConsentPurposePublication, "c2-2026-10-05", published.Add(24*time.Hour))
_, err = harness.service.GrantInSettings(t.Context(), harness.repositories, input)
var stale *consent.StaleConsentTextError
if !errors.Is(err, consent.ErrStaleConsentText) || !errors.As(err, &stale) || stale.Current != "c2-2026-10-05" {
t.Fatalf("GrantInSettings(repeat of v1) error = %v, want a stale error naming c2-2026-10-05", err)
}
if len(harness.ledger.records) != 1 || harness.ledger.records[0].ID() != first.Record.ID() {
t.Fatalf("ledger has %d records, want only the first", len(harness.ledger.records))
}
}
func TestNewServiceRefusesMissingDependencies(t *testing.T) {
harness := newHarness(t)
for name, build := range map[string]func(){
"a nil transactor": func() { consent.NewService(nil, harness.clock.Now) },
"a nil clock": func() { consent.NewService(harness.transactor, nil) },
} {
t.Run(name, func(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("NewService() did not panic")
}
}()
build()
})
}
}
func TestGrantFailuresOfTheRepositoriesKeepTheirIdentity(t *testing.T) {
t.Run("a purpose without a published text", func(t *testing.T) {
harness := newHarness(t)
harness.texts.byPurpose = map[domain.ConsentPurpose][]domain.ConsentText{}
_, err := harness.service.GrantInSettings(t.Context(), harness.repositories, consent.SettingsGrantInput{
SubjectID: uuid.New(), Purpose: domain.ConsentPurposeFSPImport,
TextVersion: "c5-2026-10-01",
})
if !errors.Is(err, outbound.ErrConsentTextNotFound) || errors.Is(err, consent.ErrStaleConsentText) {
t.Fatalf("Grant() error = %v, want ErrConsentTextNotFound and not stale", err)
}
})
t.Run("an unknown subject", func(t *testing.T) {
harness := newHarness(t)
harness.ledger.grantErrs = []error{outbound.ErrUserNotFound}
_, err := harness.service.GrantInSettings(t.Context(), harness.repositories, consent.SettingsGrantInput{
SubjectID: uuid.New(), Purpose: domain.ConsentPurposePublication,
TextVersion: harness.version(domain.ConsentPurposePublication),
})
if !errors.Is(err, outbound.ErrUserNotFound) {
t.Fatalf("Grant() error = %v, want ErrUserNotFound", err)
}
})
}
// TestPurposesAreIndependent grants every purpose but C3 and checks that the
// missing C3 neither blocks nor changes another purpose: the ledger of the
// subject is complete without it.
func TestPurposesAreIndependent(t *testing.T) {
harness := newHarness(t)
subject := uuid.New()
granted := map[domain.ConsentPurpose]uuid.UUID{}
for _, purpose := range []domain.ConsentPurpose{
domain.ConsentPurposePersonalData, domain.ConsentPurposePublication, domain.ConsentPurposeFSPImport,
} {
var result consent.GrantResult
var err error
if purpose == domain.ConsentPurposePersonalData {
result, err = harness.service.GrantAtRegistration(t.Context(), harness.repositories, subject, harness.version(purpose))
} else {
result, err = harness.service.GrantInSettings(t.Context(), harness.repositories, consent.SettingsGrantInput{
SubjectID: subject, Purpose: purpose, TextVersion: harness.version(purpose),
})
}
if err != nil || !result.Created {
t.Fatalf("grant of %s = %v, %v, want a new record", purpose, result.Created, err)
}
granted[purpose] = result.Record.ID()
}
for purpose, id := range granted {
record, err := harness.ledger.Current(t.Context(), subject, purpose)
if err != nil || record.ID() != id {
t.Errorf("Current(%s) = %s, %v, want the record of its own grant", purpose, record, err)
}
}
if _, err := harness.ledger.Current(t.Context(), subject, domain.ConsentPurposeAutoCategorization); !errors.Is(err, outbound.ErrConsentNotFound) {
t.Fatalf("Current(c3) error = %v, want ErrConsentNotFound for a subject who withheld C3", err)
}
}
func TestGrantContactIsScopedAndChecksTheVersion(t *testing.T) {
harness := newHarness(t)
input := harness.contactInput(uuid.New(), uuid.New(), uuid.New(), domain.ContactFieldEmail)
result, err := harness.service.GrantContact(t.Context(), harness.repositories, input)
if err != nil || !result.Created {
t.Fatalf("GrantContact() = %v, %v, want a new record", result.Created, err)
}
record := result.Record
if record.Purpose() != domain.ConsentPurposeContactDisclosure || record.Source() != domain.ConsentSourceInvitationAcceptance ||
record.OrganizationID() != input.OrganizationID || record.OrganizationName() != organizationName ||
record.InvitationID() != input.InvitationID || !record.Fields().Equal(input.Fields) || !record.GrantedAt().Equal(clockStart) {
t.Fatalf("GrantContact() record = %s, want the scope of its input at the application clock", record)
}
shown, err := harness.current(domain.ConsentPurposeContactDisclosure).RenderForOrganization(organizationName)
if err != nil || record.TextHash() != domain.HashConsentText(shown) {
t.Fatalf("GrantContact() hash does not prove the text shown with the organization name: %v", err)
}
t.Run("a repeat returns the existing record", func(t *testing.T) {
harness.clock.advance(time.Hour)
repeat, err := harness.service.GrantContact(t.Context(), harness.repositories, input)
if err != nil || repeat.Created || repeat.Record.ID() != record.ID() || len(harness.ledger.records) != 1 {
t.Fatalf("GrantContact(repeat) = %s, %v, %v with %d records, want the existing record", repeat.Record, repeat.Created, err, len(harness.ledger.records))
}
})
t.Run("an invitation of another subject is taken", func(t *testing.T) {
other := input
other.SubjectID = uuid.New()
_, err := harness.service.GrantContact(t.Context(), harness.repositories, other)
if !errors.Is(err, outbound.ErrConsentInvitationTaken) || len(harness.ledger.records) != 1 {
t.Fatalf("GrantContact(other subject) error = %v with %d records, want ErrConsentInvitationTaken", err, len(harness.ledger.records))
}
})
}
func TestGrantContactRefusesWhatItCannotRecord(t *testing.T) {
harness := newHarness(t)
harness.publish(domain.ConsentPurposeContactDisclosure, "c4-2026-10-05", published.Add(24*time.Hour))
valid := harness.contactInput(uuid.New(), uuid.New(), uuid.New(), domain.ContactFieldEmail, domain.ContactFieldPhone)
valid.TextVersion = "c4-2026-10-05"
tests := []struct {
name string
change func(*consent.ContactGrantInput)
want error
}{
{"a stale text version", func(in *consent.ContactGrantInput) { in.TextVersion = "c4-2026-10-01" }, consent.ErrStaleConsentText},
{"a malformed text version", func(in *consent.ContactGrantInput) { in.TextVersion = "c4/1" }, domain.ErrInvalidConsentText},
{"a padded organization name", func(in *consent.ContactGrantInput) { in.OrganizationName = " Acme " }, domain.ErrInvalidConsentText},
{"no fields", func(in *consent.ContactGrantInput) { in.Fields = domain.ContactFieldSet{} }, domain.ErrInvalidConsent},
{"no organization", func(in *consent.ContactGrantInput) { in.OrganizationID = uuid.Nil }, domain.ErrInvalidConsent},
{"no invitation", func(in *consent.ContactGrantInput) { in.InvitationID = uuid.Nil }, domain.ErrInvalidConsent},
{"no subject", func(in *consent.ContactGrantInput) { in.SubjectID = uuid.Nil }, domain.ErrInvalidConsent},
{"no terms version", func(in *consent.ContactGrantInput) { in.InvitationTermsVersion = 0 }, domain.ErrInvalidConsent},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
input := valid
test.change(&input)
_, err := harness.service.GrantContact(t.Context(), harness.repositories, input)
if !errors.Is(err, test.want) {
t.Fatalf("GrantContact() error = %v, want %v", err, test.want)
}
if harness.ledger.grantCalls != 0 || len(harness.ledger.records) != 0 {
t.Fatalf("a refused C4 grant reached the ledger")
}
})
}
}
func TestGrantInSettingsInNewTransaction(t *testing.T) {
input := func(harness *harness) consent.SettingsGrantInput {
return consent.SettingsGrantInput{
SubjectID: uuid.New(), Purpose: domain.ConsentPurposePublication,
TextVersion: harness.version(domain.ConsentPurposePublication),
}
}
t.Run("grants once in one transaction", func(t *testing.T) {
harness := newHarness(t)
result, err := harness.service.GrantInSettingsInNewTransaction(t.Context(), input(harness))
if err != nil || !result.Created || harness.transactor.calls != 1 {
t.Fatalf("GrantInSettingsInNewTransaction() = %v, %v after %d transactions, want one new record", result.Created, err, harness.transactor.calls)
}
})
t.Run("a stale version fails the transaction without retry", func(t *testing.T) {
harness := newHarness(t)
stale := input(harness)
stale.TextVersion = "c2-1999-01-01"
_, err := harness.service.GrantInSettingsInNewTransaction(t.Context(), stale)
if !errors.Is(err, consent.ErrStaleConsentText) || harness.transactor.calls != 1 || harness.transactor.lastErr == nil {
t.Fatalf("GrantInSettingsInNewTransaction(stale) error = %v after %d transactions, want one rolled back", err, harness.transactor.calls)
}
})
t.Run("a transaction conflict is retried", func(t *testing.T) {
harness := newHarness(t)
harness.ledger.grantErrs = []error{outbound.ErrTransactionConflict}
result, err := harness.service.GrantInSettingsInNewTransaction(t.Context(), input(harness))
if err != nil || !result.Created || harness.transactor.calls != 2 || len(harness.ledger.records) != 1 {
t.Fatalf("GrantInSettingsInNewTransaction(conflict) = %v, %v after %d transactions, want a record on the retry", result.Created, err, harness.transactor.calls)
}
})
t.Run("retries are bounded", func(t *testing.T) {
harness := newHarness(t)
harness.ledger.grantErrs = slices.Repeat([]error{outbound.ErrTransactionConflict}, 10)
_, err := harness.service.GrantInSettingsInNewTransaction(t.Context(), input(harness))
if !errors.Is(err, outbound.ErrTransactionConflict) || harness.transactor.calls != 3 {
t.Fatalf("GrantInSettingsInNewTransaction(persistent conflict) error = %v after %d transactions, want 3 attempts", err, harness.transactor.calls)
}
})
t.Run("another failure is not retried", func(t *testing.T) {
harness := newHarness(t)
harness.ledger.grantErrs = []error{outbound.ErrUserNotFound}
_, err := harness.service.GrantInSettingsInNewTransaction(t.Context(), input(harness))
if !errors.Is(err, outbound.ErrUserNotFound) || harness.transactor.calls != 1 {
t.Fatalf("GrantInSettingsInNewTransaction() error = %v after %d transactions, want one attempt", err, harness.transactor.calls)
}
})
t.Run("a canceled context stops the retries", func(t *testing.T) {
harness := newHarness(t)
ctx, cancel := context.WithCancel(t.Context())
harness.ledger.grantErrs = slices.Repeat([]error{outbound.ErrTransactionConflict}, 10)
harness.ledger.onGrant = cancel
_, err := harness.service.GrantInSettingsInNewTransaction(ctx, input(harness))
if !errors.Is(err, outbound.ErrTransactionConflict) || harness.transactor.calls != 1 {
t.Fatalf("GrantInSettingsInNewTransaction(canceled) error = %v after %d transactions, want one attempt", err, harness.transactor.calls)
}
})
}
// harness wires the service to in-memory repositories and a controllable
// clock.
type harness struct {
service *consent.Service
clock *fakeClock
texts *fakeTexts
ledger *fakeLedger
transactor *fakeTransactor
repositories outbound.ConsentRepositories
}
func newHarness(t *testing.T) *harness {
t.Helper()
texts := &fakeTexts{byPurpose: map[domain.ConsentPurpose][]domain.ConsentText{}}
ledger := &fakeLedger{}
repositories := &fakeRepositories{texts: texts, ledger: ledger}
clock := &fakeClock{now: clockStart}
harness := &harness{
clock: clock,
texts: texts,
ledger: ledger,
transactor: &fakeTransactor{unit: &fakeUnit{repositories: repositories}},
repositories: repositories,
}
harness.service = consent.NewService(harness.transactor, clock.Now)
for _, purpose := range allPurposes {
harness.publish(purpose, domain.ConsentTextVersion(string(purpose)+"-2026-10-01"), published)
}
return harness
}
// publish adds a text version, as a migration would.
func (harness *harness) publish(purpose domain.ConsentPurpose, version domain.ConsentTextVersion, at time.Time) {
body := "I consent to " + string(purpose) + " " + string(version)
if purpose.OrganizationScoped() {
body += " for " + domain.ConsentTextOrganizationPlaceholder
}
text, err := domain.RestoreConsentText(domain.StoredConsentText{
Purpose: string(purpose), Version: string(version), Body: body, Hash: hashBytes(body),
Kind: string(domain.ConsentTextKindDemo), PublishedAt: at,
})
if err != nil {
panic(err)
}
harness.texts.byPurpose[purpose] = append(harness.texts.byPurpose[purpose], text)
}
// current returns the text that is current at the start time of the clock.
func (harness *harness) current(purpose domain.ConsentPurpose) domain.ConsentText {
text, err := harness.texts.Current(context.Background(), purpose, clockStart)
if err != nil {
panic(err)
}
return text
}
func (harness *harness) version(purpose domain.ConsentPurpose) domain.ConsentTextVersion {
return harness.current(purpose).Version()
}
func (harness *harness) contactInput(subject, organization, invitation uuid.UUID, fields ...domain.ContactField) consent.ContactGrantInput {
set, err := domain.NewContactFieldSet(fields...)
if err != nil {
panic(err)
}
return consent.ContactGrantInput{
SubjectID: subject, OrganizationID: organization, OrganizationName: organizationName, Fields: set,
InvitationID: invitation, InvitationTermsVersion: termsVersion,
TextVersion: harness.version(domain.ConsentPurposeContactDisclosure),
}
}
func hashBytes(text string) []byte {
hash := domain.HashConsentText(text)
return hash[:]
}
type fakeClock struct{ now time.Time }
func (clock *fakeClock) Now() time.Time { return clock.now }
func (clock *fakeClock) advance(by time.Duration) { clock.now = clock.now.Add(by) }
// fakeTexts serves the texts of a purpose like the database does: the
// current one is the latest published at or before the given time.
type fakeTexts struct {
byPurpose map[domain.ConsentPurpose][]domain.ConsentText
reads int
}
func (texts *fakeTexts) Get(_ context.Context, purpose domain.ConsentPurpose, version domain.ConsentTextVersion) (domain.ConsentText, error) {
texts.reads++
for _, text := range texts.byPurpose[purpose] {
if text.Version() == version {
return text, nil
}
}
return domain.ConsentText{}, outbound.ErrConsentTextNotFound
}
func (texts *fakeTexts) Current(_ context.Context, purpose domain.ConsentPurpose, at time.Time) (domain.ConsentText, error) {
texts.reads++
var current domain.ConsentText
for _, text := range texts.byPurpose[purpose] {
if !text.PublishedAt().After(at) && (current.IsZero() || text.PublishedAt().After(current.PublishedAt())) {
current = text
}
}
if current.IsZero() {
return domain.ConsentText{}, outbound.ErrConsentTextNotFound
}
return current, nil
}
// fakeLedger keeps the records in memory with the idempotency the database
// gives: one unrevoked record per subject, purpose, and version, and one C4
// record per invitation.
type fakeLedger struct {
records []domain.ConsentRecord
grantCalls int
// grantErrs are returned by the next Grant and GrantContact calls, one
// per call, before any record is stored.
grantErrs []error
onGrant func()
}
var _ outbound.ConsentLedger = (*fakeLedger)(nil)
func (ledger *fakeLedger) nextError() error {
ledger.grantCalls++
if ledger.onGrant != nil {
ledger.onGrant()
}
if len(ledger.grantErrs) == 0 {
return nil
}
err := ledger.grantErrs[0]
ledger.grantErrs = ledger.grantErrs[1:]
return err
}
func (ledger *fakeLedger) Grant(_ context.Context, grant domain.ConsentGrant) (domain.ConsentRecord, bool, error) {
if err := ledger.nextError(); err != nil {
return domain.ConsentRecord{}, false, err
}
for _, record := range ledger.records {
if record.SubjectID() == grant.SubjectID() && record.Purpose() == grant.Purpose() && record.TextVersion() == grant.TextVersion() {
return record, false, nil
}
}
hash := grant.TextHash()
record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{
ID: grant.ID(), SubjectID: grant.SubjectID(), Purpose: string(grant.Purpose()), TextVersion: string(grant.TextVersion()),
TextHash: hash[:], Source: string(grant.Source()), State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(),
})
if err != nil {
return domain.ConsentRecord{}, false, err
}
ledger.records = append(ledger.records, record)
return record, true, nil
}
func (ledger *fakeLedger) GrantContact(_ context.Context, grant domain.ContactConsentGrant) (domain.ConsentRecord, bool, error) {
if err := ledger.nextError(); err != nil {
return domain.ConsentRecord{}, false, err
}
for _, record := range ledger.records {
if record.InvitationID() == grant.InvitationID() {
if record.SubjectID() != grant.SubjectID() {
return domain.ConsentRecord{}, false, outbound.ErrConsentInvitationTaken
}
return record, false, nil
}
}
hash := grant.TextHash()
fields := make([]string, 0, len(grant.Fields().Fields()))
for _, field := range grant.Fields().Fields() {
fields = append(fields, string(field))
}
record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{
ID: grant.ID(), SubjectID: grant.SubjectID(), Purpose: string(domain.ConsentPurposeContactDisclosure),
TextVersion: string(grant.TextVersion()), TextHash: hash[:], Source: string(domain.ConsentSourceInvitationAcceptance),
State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(), OrganizationID: grant.OrganizationID(),
OrganizationName: grant.OrganizationName(), FieldSet: fields, InvitationID: grant.InvitationID(),
InvitationTermsVersion: grant.InvitationTermsVersion(),
})
if err != nil {
return domain.ConsentRecord{}, false, err
}
ledger.records = append(ledger.records, record)
return record, true, nil
}
func (ledger *fakeLedger) Revoke(context.Context, domain.ConsentRevocation) ([]domain.ConsentRecord, error) {
panic("the consent usecase does not revoke")
}
func (ledger *fakeLedger) Current(_ context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error) {
for index := len(ledger.records) - 1; index >= 0; index-- {
if record := ledger.records[index]; record.SubjectID() == subjectID && record.Purpose() == purpose {
return record, nil
}
}
return domain.ConsentRecord{}, outbound.ErrConsentNotFound
}
func (ledger *fakeLedger) CurrentContact(context.Context, uuid.UUID, uuid.UUID) ([]domain.ConsentRecord, error) {
panic("the consent usecase does not read C4")
}
func (ledger *fakeLedger) List(context.Context, outbound.ConsentListQuery) (outbound.ConsentPage, error) {
panic("the consent usecase does not list")
}
type fakeRepositories struct {
texts *fakeTexts
ledger *fakeLedger
}
func (repositories *fakeRepositories) ConsentTexts() outbound.ConsentTextRepository {
return repositories.texts
}
func (repositories *fakeRepositories) ConsentLedger() outbound.ConsentLedger {
return repositories.ledger
}
// fakeUnit is the part of the UnitOfWork that the usecase uses; calling any
// other repository panics on the nil embedded interface.
type fakeUnit struct {
outbound.UnitOfWork
repositories *fakeRepositories
}
func (unit *fakeUnit) ConsentTexts() outbound.ConsentTextRepository {
return unit.repositories.ConsentTexts()
}
func (unit *fakeUnit) ConsentLedger() outbound.ConsentLedger {
return unit.repositories.ConsentLedger()
}
// fakeTransactor runs the callback on the fake unit and records the result.
type fakeTransactor struct {
unit *fakeUnit
calls int
lastErr error
}
func (transactor *fakeTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error {
transactor.calls++
transactor.lastErr = work(ctx, transactor.unit)
return transactor.lastErr
}