750 lines
31 KiB
Go
750 lines
31 KiB
Go
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, 1, 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.RegistrationVersion() != 1 ||
|
|
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, 1, "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, 1, 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()), RegistrationVersion: grant.RegistrationVersion(),
|
|
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) LockCurrentForUse(
|
|
ctx context.Context,
|
|
subjectID uuid.UUID,
|
|
purpose domain.ConsentPurpose,
|
|
) (domain.ConsentRecord, error) {
|
|
if purpose != domain.ConsentPurposeAutoCategorization {
|
|
return domain.ConsentRecord{}, domain.ErrInvalidConsent
|
|
}
|
|
return ledger.Current(ctx, subjectID, purpose)
|
|
}
|
|
|
|
func (ledger *fakeLedger) LockRegistration(_ context.Context, subjectID uuid.UUID, registrationVersion int64) (domain.ConsentRecord, error) {
|
|
for index := len(ledger.records) - 1; index >= 0; index-- {
|
|
if record := ledger.records[index]; record.SubjectID() == subjectID &&
|
|
record.Purpose() == domain.ConsentPurposePersonalData && record.Source() == domain.ConsentSourceRegistration &&
|
|
record.RegistrationVersion() == registrationVersion && record.State() == domain.ConsentStateActive {
|
|
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
|
|
}
|