diff --git a/backend/integration_test/consent_usecase_test.go b/backend/integration_test/consent_usecase_test.go new file mode 100644 index 0000000..4a0b21f --- /dev/null +++ b/backend/integration_test/consent_usecase_test.go @@ -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) + }) +} diff --git a/backend/internal/port/outbound/consents.go b/backend/internal/port/outbound/consents.go index 77b2075..d312579 100644 --- a/backend/internal/port/outbound/consents.go +++ b/backend/internal/port/outbound/consents.go @@ -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 diff --git a/backend/internal/usecase/consent/service.go b/backend/internal/usecase/consent/service.go new file mode 100644 index 0000000..5dc6bfe --- /dev/null +++ b/backend/internal/usecase/consent/service.go @@ -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: + } + } +} diff --git a/backend/internal/usecase/consent/service_test.go b/backend/internal/usecase/consent/service_test.go new file mode 100644 index 0000000..6651369 --- /dev/null +++ b/backend/internal/usecase/consent/service_test.go @@ -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 +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index c67f2ad..3a5a38b 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -421,6 +421,7 @@ backend/ port/inbound/ readiness and event handler input boundaries usecase/identity/ password validation before hashing (Credentials) usecase/policy/ publication of policy versions and the demo policy seed + usecase/consent/ granting of consents C1-C3 and C5 and the scoped C4 with the current-text check usecase/files/ shared private file layer: policies, opaque keys, stream limits, checksums usecase/notification/ mail requests and the consumer that stores them as deliveries usecase/notification/mailtemplate/ pure rendering of versioned service emails; the delivery consumer renders notifications with it @@ -592,7 +593,7 @@ Implemented (TASK-052) and tested, but not wired into bootstrap: registration (T ### Consent ledger -Implemented as storage, ports, and a read contract (TASK-062): migration `backend/db/migrations/00009_create_consent_ledger.sql`, queries in `backend/db/queries/consents.sql`, domain types in `backend/internal/domain/consent.go`, the ports in `backend/internal/port/outbound/consents.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/consents.go`, and `ListMyConsents` in the public contract ([api/README.en.md](../../api/README.en.md#consents)). Granting C1-C3 and C5 with a current-version check (TASK-063), revocation with its downstream effects and the HTTP handler (TASK-064), C1 in the registration transaction (TASK-053), and C4 in the invitation acceptance (TASK-201) are planned; no usecase writes the ledger yet. +Implemented as storage, ports, and a read contract (TASK-062): migration `backend/db/migrations/00009_create_consent_ledger.sql`, queries in `backend/db/queries/consents.sql`, domain types in `backend/internal/domain/consent.go`, the ports in `backend/internal/port/outbound/consents.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/consents.go`, and `ListMyConsents` in the public contract ([api/README.en.md](../../api/README.en.md#consents)). Granting C1-C3 and C5 with a current-version check is implemented as the usecase `consent.Service` (TASK-063, see [Consent usecase](#consent-usecase)). Revocation with its downstream effects and the HTTP handler (TASK-064), C1 in the registration transaction (TASK-053), and C4 in the invitation acceptance (TASK-201) are planned; no product flow calls the usecase yet. The consents C1-C5 of PRD FR01 are independent purposes: a grant or a revocation of one never changes another. @@ -603,10 +604,10 @@ The consents C1-C5 of PRD FR01 are independent purposes: a grant or a revocation Decisions: - Text binding. A foreign key on (`purpose`, `text_version`) refuses a version that was never published for the purpose, and a BEFORE INSERT trigger refuses a version published after the grant time (`consent_records_text_published`). For C1-C3 and C5 a second foreign key over a generated column requires `text_hash` to equal the hash of the published text. For C4 the same trigger requires `text_hash` to equal the SHA-256 of the published text with `organization_name` filled in (`consent_records_c4_text_hash`). The domain computes that hash itself in `domain.NewContactConsentGrant` from the published `ConsentText` and the name, so no caller supplies hash bytes, and a client can invent neither a version nor a hash. The stored name is the snapshot that proves the shown text; a later rename of the organization does not change it, and the read model returns it as `ConsentOrganization.name`. -- History. The only UPDATE a trigger allows is the revocation stamp on an unrevoked row with every other column unchanged (`consent_records_immutable`). A newer text version is a new row next to the older one; a grant after a revocation is a new row. The state (`active`, `superseded`, `revoked`) is computed by the queries, never stored: among the unrevoked rows of a subject and purpose other than C4, the row granted last (by `granted_at`, then ID) is `active` and the others are `superseded`, whatever their versions. The ledger therefore accepts any published version, and the grant usecase (TASK-063) must check that the version is the current text before it calls `Grant`. A partial unique index keeps one unrevoked row per subject, purpose, and version, so a repeated or concurrent grant returns the existing record; a unique index on `invitation_id` keeps one C4 row per invitation, revoked or not, so a revoked C4 never comes back. +- History. The only UPDATE a trigger allows is the revocation stamp on an unrevoked row with every other column unchanged (`consent_records_immutable`). A newer text version is a new row next to the older one; a grant after a revocation is a new row. The state (`active`, `superseded`, `revoked`) is computed by the queries, never stored: among the unrevoked rows of a subject and purpose other than C4, the row granted last (by `granted_at`, then ID) is `active` and the others are `superseded`, whatever their versions. The ledger therefore accepts any published version, and the grant usecase `consent.Service` (TASK-063) checks that the version is the current text before it calls `Grant`. A partial unique index keeps one unrevoked row per subject, purpose, and version, so a repeated or concurrent grant returns the existing record; a unique index on `invitation_id` keeps one C4 row per invitation, revoked or not, so a revoked C4 never comes back. - Revocation. `ConsentLedger.Revoke` stamps every unrevoked row of the purpose, superseded rows included, and for C4 only those of one organization. A repeat finds nothing and keeps the first stamp. A revocation time before the grant time of a row, from clock skew between instances, is stamped at the grant time (`greatest`), so the `consent_records_revocation_stamp` CHECK stays a backstop. The downstream effects of a revocation (deletion request for C1, closing publication and grants for C2 and C4, the manual path for C3, stopping the import for C5) belong to TASK-064 and are not implemented. - Retention and deletion. PRD 7.3 plans to keep consents for three years, which can outlive the account, so `subject_id` references `users` with `ON DELETE RESTRICT`, and a BEFORE DELETE trigger refuses deleting a row whose subject is a confirmed account (`consent_records_retained`). Rows of an unconfirmed account may be deleted, because a registration that the email owner never confirmed is not evidence of anyone's consent: the unverified account cleanup deletes the rows of the accounts it removes in the same statement, and `UpdateRegistration` deletes the registration C1 of the account it re-registers (see below). TRUNCATE fires no row trigger and stays allowed for test isolation. Whether a deleted account leaves its ledger, a tombstone, or nothing is decided by the C1 deletion request of TASK-064 and the account deletion procedure that executes it, which has no MVP task yet; the retention rule extends the delete condition in its own migration. -- Re-registration. An unverified account keeps its `users.id` when the same email registers again, so the earlier registrant's C1 would otherwise stand for the new one. The `UpdateUserRegistration` statement deletes the C1 rows with the source `registration` of the account it updates, and only when the update applies. This is a binding requirement for TASK-053: the registration usecase calls `UpdateRegistration` and records the new C1 with `ConsentLedger().Grant` in the same transaction. +- Re-registration. An unverified account keeps its `users.id` when the same email registers again, so the earlier registrant's C1 would otherwise stand for the new one. The `UpdateUserRegistration` statement deletes the C1 rows with the source `registration` of the account it updates, and only when the update applies. This is a binding requirement for TASK-053: the registration usecase calls `UpdateRegistration` and records the new C1 with `consent.Service.GrantAtRegistration`, strictly after `UpdateRegistration`, in the same transaction (see [Consent usecase](#consent-usecase)). - C2 and the published field set. A C2 row proves the consent to the publication text, not which fields were published. The published field set and its changes are evidence of the publication history of TASK-088, which must keep them with their times. Adding a field scope to C2 rows later is an additive migration and contract change. - C4 in a business transaction. `UnitOfWork.ConsentLedger().GrantContact` takes a `domain.ContactConsentGrant`, which only `domain.NewContactConsentGrant` builds and which requires the C4 text, the organization and its name, a non-empty field set, the invitation, and its terms version; `domain.NewConsentGrant` refuses C4. The acceptance (TASK-201) calls it in the transaction that moves the invitation to `accepted`, creates the grant, and writes the audit event, so all of them commit or roll back together. A repeated acceptance gets the existing record with `created` false and compares its scope; an invitation whose C4 belongs to another subject returns `ErrConsentInvitationTaken`. - Cleanup race. The cleanup checks consent rows in its statement snapshot. A consent committed for a candidate account after that snapshot but before the account lock fails the restricting foreign key at the end of the statement (SQLSTATE 23001); the adapter reports it as `ErrTransactionConflict`, nothing is deleted, and the next run sees the consent. @@ -620,6 +621,22 @@ What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWo - `ConsentLedger().Grant` and `GrantContact` return the new record with `created` true or the existing one with `created` false. An unknown subject returns `ErrUserNotFound`, an unknown version `ErrConsentTextNotFound`, a version published later `ErrConsentTextNotPublished`, and a hash that does not match the published text (for C4 with the stored name) `ErrConsentTextMismatch`; these come from the database and abort a surrounding transaction. A duplicate does not. A grant whose conflicting record was revoked between its two statements returns `ErrTransactionConflict`. - `Revoke` returns the rows it stamped. `Current` returns the newest unrevoked C1-C3 or C5 record or `ErrConsentNotFound`; `CurrentContact` returns the unrevoked C4 records of one organization. `List` pages the subject's ledger newest first, optionally by state. +### Consent usecase + +Implemented (TASK-063): `consent.Service` in `backend/internal/usecase/consent/`. It is not wired into bootstrap yet, because no handler or registration flow calls it; the first caller builds it with `consent.NewService(transactor, clock)`, the `Transactor` and the application clock that the other usecases already receive. A nil transactor or clock panics at construction, so a wiring mistake shows at startup and not at the first grant. + +- Entry points fix the source. `GrantAtRegistration(ctx, repositories, subjectID, version)` records C1 with the source `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` records C1, C2, C3, or C5 with the source `consent_settings`. Neither takes a source or a time, so a handler cannot read either from the client. `repositories` is an `outbound.ConsentRepositories`: pass the `UnitOfWork` of a business operation and the grant commits or rolls back with it. The registration (TASK-053) creates the account and records C1 in one transaction on the subject ID alone, so no session is needed. `GrantInSettingsInNewTransaction` opens its own transaction for a grant that is not part of another operation, and retries an `ErrTransactionConflict` up to three attempts in total with a short jittered wait (10 ms plus up to 10 ms) between them, which is safe because a repeat is idempotent; the wait ends at once when the context is canceled. +- Re-registration order. For an unverified account that registers again, call `GrantAtRegistration` strictly after `UserRepository.UpdateRegistration` in the same transaction. `UpdateRegistration` deletes the registration C1 of the earlier registrant, and a 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. The integration test shows both orders. +- Version check before the email branch. `CheckTextVersion(ctx, repositories, purpose, version)` returns the current text when `version` is current and fails like a grant otherwise, without writing anything. The registration (TASK-053) must call it with C1 and the submitted version before it branches on a new or an existing email; otherwise a stale version would be refused only for new addresses, and the difference would reveal which accounts exist. +- Current text only. A grant reads `ConsentTexts().Current` at the application time and refuses any other version with `*StaleConsentTextError`, which matches `ErrStaleConsentText` and carries the purpose, the requested version, and the current one, so a handler can map it to one problem code and show the new text. An older version, a version that is scheduled but not yet published, and a version that never existed are all stale. The ledger accepts any published version, so this check is what keeps a grant of an outdated text out. The check and the insert are not locked against a publication between them: texts are published by migrations, and a grant that named the current text when it was checked is valid. +- Server time. The input has no time field. The grant uses one reading of the injected clock for the check and for the record time; a client cannot choose the time. The database still refuses a version published after that time. +- Idempotency. A repeat of the same subject, purpose, and current version returns the existing unrevoked record with `Created` false, keeps its first time, stores nothing, and does not abort a surrounding transaction. A grant after a revocation is a new record. 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, and the ledger keeps its one record. +- C4 only through its scope. `GrantInSettings` refuses C4 with `ErrScopedConsentRequired` before it reads anything. `GrantContact(ctx, repositories, input)` is the explicitly scoped operation for the invitation acceptance (TASK-201): the input carries the organization and the name shown, the field set, the invitation, the invitation terms version, and the C4 text version. It checks that the C4 text is current, lets `domain.NewContactConsentGrant` hash the text as shown, and calls `ConsentLedger().GrantContact` in the caller's transaction. A repeat of the same subject and invitation returns the existing record with `Created` false; the caller compares its scope. The text check comes first, so a repeat after a newer C4 text was published is stale; the acceptance that wants to answer such a repeat with the earlier result must find its existing record before it calls. +- C3 may be withheld. The purposes are independent: no grant requires, implies, or changes another, and no code path requires an active C3 for the profile, the manual assessment path, or another function. A subject without C3 has no C3 record, and `Current` returns `ErrConsentNotFound` for it, which is not an error state of the account. Whoever reads C3 (the manual assessment request of TASK-315, the revocation of TASK-064) treats a missing record as "not given" and keeps the manual path open. +- No revocation here. `Revoke` stays on the ledger port, and TASK-064 calls it with the downstream effects and the outbox events in one transaction. +- Errors keep their identity: a stale version, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (the purpose has no published text), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent`, and `domain.ErrInvalidConsentText`. `outbound.ErrTransactionConflict` is the one that needs action: the ledger returns it, without aborting the transaction, when the record of a repeat was revoked between its insert and its select. A caller inside a `UnitOfWork` must return it, roll the transaction back, and retry the whole operation; `GrantInSettingsInNewTransaction` does so itself. Mapping the other errors to problem codes belongs to the handlers (TASK-064, TASK-053, TASK-201). +- Demo texts need a release gate. The texts that the migration publishes have the kind `demo`: synthetic, without a legal review. Nothing in the usecase distinguishes them from texts of the operator, so a deployment that accepts real data would record consent to a demo text. Before real data are accepted (PRD 7.3), a release gate must check that the current text of every purpose has the kind `operator`; the owner is the release gate or TASK-064, and neither exists yet. + ## Frontend The target FSD structure has app for router and providers, pages for screens, widgets for larger UI blocks, features for actions, entities for product concepts, and shared for API, UI, and utilities. Imports point down; generated DTOs do not import product entities. TanStack Query owns server state, forms own drafts, and URL parameters own filters and search IDs. Add Zustand only for a specific shared client-state need. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 8ca6d9b..af0383f 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -226,6 +226,7 @@ Unit tests (`make -C backend test`) cover the ledger rules without a database: - `internal/domain/` (`consent_test.go`): only `c1` to `c5` are purposes and only C4 is organization scoped; a text version follows the contract pattern of 1 to 64 characters; a text hash must be 32 bytes and not all zero; a stored text whose body no longer matches its hash, a C4 text without the `{organization}` placeholder, and another text with it are refused; the rendered C4 text hashes differently per organization and from its template, and an empty, padded, or multi-line organization name is refused. `NewConsentGrant` refuses C4, an empty or malformed version, a missing hash, subject, or time, and a source that the purpose does not allow; `NewContactConsentGrant` requires the C4 text, the organization with a valid name, a field set, the invitation, and a positive terms version, and hashes the text as shown for that name. Grants and revocations print and log no subject, organization, name, or field. A field set is canonical in any input order and refuses empty, repeated, unknown, and more than four fields. `RestoreConsentRecord` refuses what the database refuses, and a record prints and logs only its ID, purpose, and state. - `internal/adapter/secondary/postgres/` (`consents_test.go`): ledger constraint errors map to their sentinels by SQLSTATE and constraint name without the row detail, the restricting consent key in the cleanup maps to `ErrTransactionConflict`, invalid input fails before any statement, every generated row type converts to one record row, and the stored field set keeps the order the database accepts. +- `internal/usecase/consent/` (`service_test.go`, with an in-memory text repository, ledger, transactor, and a controllable clock): a grant of C1, C2, C3, and C5 records the current text version and hash, the source of its entry point (`GrantAtRegistration` fixes C1 and `registration`, `GrantInSettings` fixes `consent_settings`), and the time of the injected clock, never another time; a grant with an older, unknown, or scheduled version fails with `ErrStaleConsentText`, names the current version, and never reaches the ledger; granting version one, publishing version two, and repeating version one is stale and leaves one record; `CheckTextVersion` returns the current text, fails stale for an older, unknown, and scheduled version, refuses an unknown purpose and a malformed version, and never touches the ledger; C4 on the generic path fails with `ErrScopedConsentRequired` before any repository is read; a malformed or empty version, an unknown purpose, and a nil subject are refused; a repeat returns the existing record with `Created` false and its first time, and the ledger keeps one record; failures of the repositories (no published text, unknown subject) keep their sentinel and a missing text is not reported as stale; a subject who withheld C3 has the other purposes with their own records and no C3 record; `GrantContact` records the scope, the source `invitation_acceptance`, and the hash of the text as shown, returns the existing record for a repeat, reports an invitation of another subject as taken, and refuses a stale C4 version, a padded name, and missing fields, organization, invitation, subject, or terms version; `GrantInSettingsInNewTransaction` retries a transaction conflict after a wait, stops after three attempts, does not retry another error or a canceled context, and rolls back a stale grant; `NewService` panics on a nil transactor or clock. - `internal/adapter/primary/http/` (`router_test.go`): `ListMyConsents` answers 501 after validation for a session and 400 with the query pointer for an unknown state, a limit over 100, and a malformed cursor; under `DenyAllSecurity` it answers 401 with or without a cookie and with a `subject_id` parameter; the DTOs carry no hash, subject, or contact field, the parameters are only the state and the page, and the contract example decodes and validates. - `frontend/src/shared/api/consent-contract.test.ts`: the generated Zod schemas accept a C4 record with its scope and a revoked unscoped record, refuse an unknown purpose, state, or source, an empty or malformed version, an empty or oversized field set, an unknown contact kind, and a terms version below 1, require every nullable field, and drop a hash or subject; the operation takes only the state and page parameters. @@ -248,7 +249,17 @@ Unit tests (`make -C backend test`) cover the ledger rules without a database: - Twenty rounds of a grant racing a revocation return no error other than `ErrTransactionConflict` and never leave more than one unrevoked record of the version. - With only the consent row of a stale account locked, the cleanup on a session with a 200 ms lock timeout skips the account without waiting, and deletes it after the lock is gone. -`TestPostgresMigrations` rolls migration 00009 back with the others and checks that no table or function remains. The integration tests of identity, mail delivery, and mail quotas name `consent_records` in their TRUNCATE of `users`. The suite does not cover the grant and revocation usecases or the HTTP handler, and the cleanup race that ends in SQLSTATE 23001 is covered only by the unit test of its mapping, because its window cannot be reproduced deterministically. +`TestConsentGrants` in `backend/integration_test/consent_usecase_test.go` runs the usecase on the bootstrap database with a fixed application clock, a second C1 text, and a C5 text scheduled after the clock: + +- Registration: `UserRepository.Create` and `GrantAtRegistration` of C1 run in one `Transactor` transaction with no session (the sessions table stays empty) and commit one account and one C1 at the application time with the current text version. C2 and C5 follow as separate operations, each with its own active record; C3 is withheld and has no record while the others stand; a C3 granted later and revoked leaves C1, C2, and C5 active. +- Atomicity: a transaction that fails after the account and C1 were written leaves neither, and a grant for a subject without an account fails with `ErrUserNotFound` and stores nothing. +- Idempotency and versions: a repeat in its own transaction and in a business transaction returns the first record and its time and stores no row, and a repeat does not abort the transaction. An outdated C1 version, a scheduled C5 version, and an unknown C3 version fail with a stale error that names the current version and store nothing; the current C1 version goes through and the outdated one stays refused. A grant after a revocation is a new row. Eight concurrent repeats create exactly one row. +- Republication: after C3 version one is granted and version two is published, a repeat of version one is stale, names version two, and leaves one row and the first record as the current C3. +- Re-registration: `UpdateRegistration` followed by `GrantAtRegistration` in one transaction returns `created` true with a new record and leaves exactly one C1. The opposite order is shown as a hazard: the grant finds the earlier registrant's C1 and returns it with `created` false, the update then deletes it, and the account ends with no C1. +- C4: the generic path refuses it and stores nothing; `GrantContact` in a transaction stores the organization, the name, the fields, the invitation, and the source `invitation_acceptance`; a repeat returns the same record, an outdated C4 version is stale, and the C4 does not create a C2. +- Restart: after the pool is closed, a new pool, store, and usecase list the same four records in order with their states, the revocation stamp and source, and the original grant times, and a repeat grant through the new instance stores nothing. + +`TestPostgresMigrations` rolls migration 00009 back with the others and checks that no table or function remains. The integration tests of identity, mail delivery, and mail quotas name `consent_records` in their TRUNCATE of `users`. The suite does not cover the revocation usecase, the HTTP handler, or the call of the consent usecase from registration and the invitation acceptance, and the cleanup race that ends in SQLSTATE 23001 is covered only by the unit test of its mapping, because its window cannot be reproduced deterministically. ## Future software validation diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 0686d6a..54cec43 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -421,6 +421,7 @@ backend/ port/inbound/ inbound границы readiness и обработчиков событий usecase/identity/ проверка пароля до хеширования (Credentials) usecase/policy/ публикация версий политики и начальное заполнение демонстрационной политики + usecase/consent/ выдача согласий C1-C3 и C5 и C4 со scope с проверкой актуального текста usecase/files/ общий закрытый файловый слой: политики, непрозрачные ключи, лимиты потока, контрольные суммы usecase/notification/ запросы писем и обработчик, который сохраняет их как доставки usecase/notification/mailtemplate/ чистый рендеринг версионированных служебных писем; обработчик доставки рендерит им уведомления @@ -592,7 +593,7 @@ contact_grant относится к паре кандидат-компания ### Журнал согласий -Реализованы хранение, порты и контракт чтения (TASK-062): миграция `backend/db/migrations/00009_create_consent_ledger.sql`, запросы в `backend/db/queries/consents.sql`, доменные типы в `backend/internal/domain/consent.go`, порты в `backend/internal/port/outbound/consents.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/consents.go` и `ListMyConsents` в публичном контракте ([api/README.md](../../api/README.md#согласия)). Выдача C1-C3 и C5 с проверкой актуальной версии (TASK-063), отзыв с последствиями и HTTP-обработчик (TASK-064), C1 в транзакции регистрации (TASK-053) и C4 при принятии приглашения (TASK-201) запланированы; ни один usecase пока не пишет в журнал. +Реализованы хранение, порты и контракт чтения (TASK-062): миграция `backend/db/migrations/00009_create_consent_ledger.sql`, запросы в `backend/db/queries/consents.sql`, доменные типы в `backend/internal/domain/consent.go`, порты в `backend/internal/port/outbound/consents.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/consents.go` и `ListMyConsents` в публичном контракте ([api/README.md](../../api/README.md#согласия)). Выдача C1-C3 и C5 с проверкой актуальной версии реализована как usecase `consent.Service` (TASK-063, см. [Usecase согласий](#usecase-согласий)). Отзыв с последствиями и HTTP-обработчик (TASK-064), C1 в транзакции регистрации (TASK-053) и C4 при принятии приглашения (TASK-201) запланированы; ни один продуктовый поток пока не вызывает usecase. Согласия C1-C5 из PRD FR01 - независимые цели: выдача или отзыв одной цели никогда не меняет другую. @@ -603,10 +604,10 @@ contact_grant относится к паре кандидат-компания Решения: - Привязка к тексту. Внешний ключ на (`purpose`, `text_version`) отклоняет версию, которая для цели не публиковалась, а триггер BEFORE INSERT отклоняет версию, опубликованную позже времени выдачи (`consent_records_text_published`). Для C1-C3 и C5 второй внешний ключ через генерируемую колонку требует, чтобы `text_hash` совпадал с хэшем опубликованного текста. Для C4 тот же триггер требует, чтобы `text_hash` был SHA-256 опубликованного текста с подставленным `organization_name` (`consent_records_c4_text_hash`). Домен сам считает этот хэш в `domain.NewContactConsentGrant` из опубликованного `ConsentText` и названия, поэтому вызывающий код не передает байты хэша, а клиент не может придумать ни версию, ни хэш. Сохраненное название - снимок, который доказывает показанный текст; последующее переименование организации его не меняет, и модель чтения возвращает его как `ConsentOrganization.name`. -- История. Единственный UPDATE, который пропускает триггер, - отметка отзыва у неотозванной строки без изменения остальных колонок (`consent_records_immutable`). Новая версия текста - новая строка рядом со старой; выдача после отзыва - новая строка. Состояние (`active`, `superseded`, `revoked`) вычисляют запросы, оно не хранится: среди неотозванных строк субъекта и цели, кроме C4, строка, выданная последней (по `granted_at`, затем по ID), - `active`, остальные - `superseded`, независимо от их версий. Поэтому журнал принимает любую опубликованную версию, а usecase выдачи (TASK-063) обязан проверить, что версия - актуальный текст, до вызова `Grant`. Частичный уникальный индекс оставляет одну неотозванную строку на субъекта, цель и версию, поэтому повторная или конкурентная выдача возвращает существующую запись; уникальный индекс по `invitation_id` оставляет одну строку C4 на приглашение, отозванную или нет, поэтому отозванное C4 не возвращается. +- История. Единственный UPDATE, который пропускает триггер, - отметка отзыва у неотозванной строки без изменения остальных колонок (`consent_records_immutable`). Новая версия текста - новая строка рядом со старой; выдача после отзыва - новая строка. Состояние (`active`, `superseded`, `revoked`) вычисляют запросы, оно не хранится: среди неотозванных строк субъекта и цели, кроме C4, строка, выданная последней (по `granted_at`, затем по ID), - `active`, остальные - `superseded`, независимо от их версий. Поэтому журнал принимает любую опубликованную версию, а usecase выдачи `consent.Service` (TASK-063) проверяет, что версия - актуальный текст, до вызова `Grant`. Частичный уникальный индекс оставляет одну неотозванную строку на субъекта, цель и версию, поэтому повторная или конкурентная выдача возвращает существующую запись; уникальный индекс по `invitation_id` оставляет одну строку C4 на приглашение, отозванную или нет, поэтому отозванное C4 не возвращается. - Отзыв. `ConsentLedger.Revoke` ставит отметку на все неотозванные строки цели, включая `superseded`, а для C4 - только на строки одной организации. Повтор ничего не находит и сохраняет первую отметку. Время отзыва раньше времени выдачи строки, из-за расхождения часов между экземплярами, записывается временем выдачи (`greatest`), поэтому CHECK `consent_records_revocation_stamp` остается последней защитой. Последствия отзыва (запрос удаления для C1, закрытие публикации и grants для C2 и C4, ручной путь для C3, остановка импорта для C5) относятся к TASK-064 и не реализованы. - Хранение и удаление. PRD 7.3 планирует хранить согласия три года, и это может быть дольше жизни аккаунта, поэтому `subject_id` ссылается на `users` с `ON DELETE RESTRICT`, а триггер BEFORE DELETE запрещает удалять строку подтвержденного аккаунта (`consent_records_retained`). Строки неподтвержденного аккаунта удалять можно, потому что регистрация, которую владелец адреса не подтвердил, не доказывает чье-либо согласие: очистка неподтвержденных аккаунтов удаляет строки удаляемых аккаунтов в том же запросе, а `UpdateRegistration` удаляет регистрационное C1 повторно регистрируемого аккаунта (см. ниже). TRUNCATE не вызывает строковый триггер и остается разрешенным для изоляции тестов. Оставит ли удаленный аккаунт журнал, tombstone или ничего, решают запрос удаления по C1 из TASK-064 и процедура удаления аккаунта, которая его исполняет и пока не имеет задачи в MVP; правило хранения расширит условие удаления своей миграцией. -- Повторная регистрация. Неподтвержденный аккаунт сохраняет `users.id`, когда тот же email регистрируется снова, поэтому иначе C1 прежнего регистранта стояло бы за новым. Запрос `UpdateUserRegistration` удаляет строки C1 с источником `registration` обновляемого аккаунта, и только если обновление применилось. Это обязательное требование для TASK-053: usecase регистрации вызывает `UpdateRegistration` и записывает новое C1 через `ConsentLedger().Grant` в той же транзакции. +- Повторная регистрация. Неподтвержденный аккаунт сохраняет `users.id`, когда тот же email регистрируется снова, поэтому иначе C1 прежнего регистранта стояло бы за новым. Запрос `UpdateUserRegistration` удаляет строки C1 с источником `registration` обновляемого аккаунта, и только если обновление применилось. Это обязательное требование для TASK-053: usecase регистрации вызывает `UpdateRegistration` и записывает новое C1 через `consent.Service.GrantAtRegistration` строго после `UpdateRegistration` в той же транзакции (см. [Usecase согласий](#usecase-согласий)). - C2 и набор публикуемых полей. Строка C2 доказывает согласие с текстом публикации, а не то, какие поля опубликованы. Набор опубликованных полей и его изменения - доказательства истории публикации из TASK-088, которая обязана хранить их со временем. Добавить scope полей в строки C2 позже - аддитивное изменение миграции и контракта. - C4 в бизнес-транзакции. `UnitOfWork.ConsentLedger().GrantContact` принимает `domain.ContactConsentGrant`, который строит только `domain.NewContactConsentGrant` и который требует текст C4, организацию и ее название, непустой набор полей, приглашение и его версию условий; `domain.NewConsentGrant` отклоняет C4. Принятие приглашения (TASK-201) вызывает его в транзакции, которая переводит приглашение в `accepted`, создает grant и пишет событие аудита, поэтому все это фиксируется или откатывается вместе. Повторное принятие получает существующую запись с `created` false и сравнивает ее scope; для приглашения, чье C4 принадлежит другому субъекту, возвращается `ErrConsentInvitationTaken`. - Гонка очистки. Очистка проверяет строки согласий в снимке своего запроса. Согласие, зафиксированное для аккаунта-кандидата после этого снимка, но до блокировки аккаунта, нарушает ограничивающий внешний ключ в конце запроса (SQLSTATE 23001); адаптер возвращает его как `ErrTransactionConflict`, ничего не удаляется, а следующий запуск видит согласие. @@ -620,6 +621,22 @@ contact_grant относится к паре кандидат-компания - `ConsentLedger().Grant` и `GrantContact` возвращают новую запись с `created` true или существующую с `created` false. Неизвестный субъект возвращает `ErrUserNotFound`, неизвестная версия - `ErrConsentTextNotFound`, версия, опубликованная позже, - `ErrConsentTextNotPublished`, хэш, не совпадающий с опубликованным текстом (для C4 - с сохраненным названием), - `ErrConsentTextMismatch`; эти ошибки приходят из базы и прерывают внешнюю транзакцию. Дубликат ее не прерывает. Выдача, чья конфликтующая запись была отозвана между двумя ее запросами, возвращает `ErrTransactionConflict`. - `Revoke` возвращает строки, на которые поставил отметку. `Current` возвращает новейшую неотозванную запись C1-C3 или C5 либо `ErrConsentNotFound`; `CurrentContact` возвращает неотозванные записи C4 одной организации. `List` выдает журнал субъекта страницами от новых к старым, при необходимости по состоянию. +### Usecase согласий + +Реализовано (TASK-063): `consent.Service` в `backend/internal/usecase/consent/`. В bootstrap он пока не подключен, потому что его не вызывает ни обработчик, ни регистрация; первый вызывающий код создаст его через `consent.NewService(transactor, clock)` с `Transactor` и часами приложения, которые получают остальные usecase. Нулевой transactor или часы вызывают панику при создании, поэтому ошибка сборки видна при старте, а не при первой выдаче. + +- Точки входа фиксируют источник. `GrantAtRegistration(ctx, repositories, subjectID, version)` записывает C1 с источником `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` записывает C1, C2, C3 или C5 с источником `consent_settings`. Ни одна не принимает источник или время, поэтому обработчик не может взять их от клиента. `repositories` - это `outbound.ConsentRepositories`: если передать `UnitOfWork` бизнес-операции, выдача фиксируется или откатывается вместе с ней. Регистрация (TASK-053) создает аккаунт и записывает C1 в одной транзакции только по ID субъекта, поэтому сессия не нужна. `GrantInSettingsInNewTransaction` открывает собственную транзакцию для выдачи вне другой операции и повторяет `ErrTransactionConflict` до трех попыток всего с короткой случайной паузой (10 мс плюс до 10 мс) между ними; это безопасно, потому что повтор идемпотентен, а пауза прерывается сразу при отмене контекста. +- Порядок при повторной регистрации. Для неподтвержденного аккаунта, который регистрируется снова, вызывайте `GrantAtRegistration` строго после `UserRepository.UpdateRegistration` в той же транзакции. `UpdateRegistration` удаляет регистрационное C1 прежнего регистранта, а выдача, выполненная до него, нашла бы эту запись, вернула ее с `Created` false и после удаления оставила бы аккаунт без C1. Интеграционный тест показывает оба порядка. +- Проверка версии до ветвления по email. `CheckTextVersion(ctx, repositories, purpose, version)` возвращает актуальный текст, если `version` актуальна, а иначе завершается как выдача, ничего не записывая. Регистрация (TASK-053) обязана вызвать ее с C1 и присланной версией до ветвления на новый или существующий email; иначе устаревшая версия отклонялась бы только для новых адресов, и разница выдала бы, какие аккаунты существуют. +- Только актуальный текст. Выдача читает `ConsentTexts().Current` на время приложения и отклоняет любую другую версию ошибкой `*StaleConsentTextError`, которая совпадает с `ErrStaleConsentText` и содержит цель, запрошенную и актуальную версии, поэтому обработчик может сопоставить ее одному коду problem и показать новый текст. Устаревшая версия, версия, которая запланирована, но еще не опубликована, и версия, которой никогда не было, считаются устаревшими. Журнал принимает любую опубликованную версию, поэтому именно эта проверка не пускает выдачу устаревшего текста. Проверка и вставка не блокируются от публикации между ними: тексты публикуют миграции, а выдача, назвавшая актуальный текст на момент проверки, допустима. +- Серверное время. Во входе нет поля времени. Выдача берет одно чтение внедренных часов для проверки и для времени записи; клиент не выбирает время. База по-прежнему отклоняет версию, опубликованную после этого времени. +- Идемпотентность. Повтор того же субъекта, цели и актуальной версии возвращает существующую неотозванную запись с `Created` false, сохраняет ее первое время, ничего не записывает и не прерывает внешнюю транзакцию. Выдача после отзыва - новая запись. Повтор с более старой версией после публикации нового текста - не повтор, а устаревшая версия: субъект должен увидеть новый текст, а в журнале остается одна запись. +- C4 только через scope. `GrantInSettings` отклоняет C4 ошибкой `ErrScopedConsentRequired`, ничего не прочитав. `GrantContact(ctx, repositories, input)` - явно ограниченная операция для принятия приглашения (TASK-201): вход содержит организацию и показанное название, набор полей, приглашение, версию условий приглашения и версию текста C4. Она проверяет, что текст C4 актуален, поручает `domain.NewContactConsentGrant` посчитать хэш показанного текста и вызывает `ConsentLedger().GrantContact` в транзакции вызывающего кода. Повтор того же субъекта и приглашения возвращает существующую запись с `Created` false; scope сравнивает вызывающий код. Проверка текста идет первой, поэтому повтор после публикации нового текста C4 считается устаревшим; принятие, которое хочет ответить на такой повтор прежним результатом, должно найти свою запись до вызова. +- C3 можно не давать. Цели независимы: ни одна выдача не требует, не подразумевает и не меняет другую, и ни один путь кода не требует активного C3 для профиля, ручного пути оценки или другой функции. У субъекта без C3 нет записи C3, и `Current` возвращает для него `ErrConsentNotFound`; это не ошибочное состояние аккаунта. Код, который читает C3 (запрос ручной оценки TASK-315, отзыв TASK-064), считает отсутствие записи состоянием "не дано" и оставляет ручной путь доступным. +- Отзыва здесь нет. `Revoke` остается на порте журнала, а TASK-064 вызывает его вместе с последующими эффектами и событиями outbox в одной транзакции. +- Ошибки сохраняют идентичность: устаревшая версия, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (у цели нет опубликованного текста), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent` и `domain.ErrInvalidConsentText`. Действия требует `outbound.ErrTransactionConflict`: журнал возвращает его, не прерывая транзакцию, когда запись повтора была отозвана между вставкой и выборкой. Вызывающий код внутри `UnitOfWork` обязан вернуть эту ошибку, откатить транзакцию и повторить всю операцию; `GrantInSettingsInNewTransaction` делает это сам. Сопоставление остальных ошибок с кодами problem - дело обработчиков (TASK-064, TASK-053, TASK-201). +- Демо-тексты требуют проверки перед выпуском. Тексты, которые публикует миграция, имеют вид `demo`: синтетические, без юридической проверки. Usecase не отличает их от текстов оператора, поэтому установка, принимающая реальные данные, записала бы согласие на демо-текст. До приема реальных данных (PRD 7.3) проверка перед выпуском должна убедиться, что актуальный текст каждой цели имеет вид `operator`; владелец - проверка перед выпуском или TASK-064, и ни той, ни другой пока нет. + ## Frontend Целевая FSD-структура: app композирует router/providers, pages задают экраны, widgets - крупные блоки, features - действия, entities - понятия продукта, shared - API, UI и утилиты. Импорты направлены вниз; generated DTO не импортируют product entities. TanStack Query владеет server state; формы владеют черновиками; фильтры и ID поиска живут в URL. Zustand добавляется только при конкретной потребности. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 82e25fa..3ceb376 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -226,6 +226,7 @@ Unit-тесты (`make -C backend test`) проверяют правила жу - `internal/domain/` (`consent_test.go`): целями считаются только `c1`-`c5`, и только C4 привязано к организации; версия текста следует шаблону контракта из 1-64 символов; хэш текста обязан иметь 32 байта и не быть нулевым; отклоняются сохраненный текст, который больше не совпадает со своим хэшем, текст C4 без плейсхолдера `{organization}` и другой текст с ним; показанный текст C4 дает разный хэш для разных организаций и отличается от хэша шаблона, а пустое, окруженное пробелами или многострочное название организации отклоняется. `NewConsentGrant` отклоняет C4, пустую или неверную версию, отсутствие хэша, субъекта или времени и источник, который цель не допускает; `NewContactConsentGrant` требует текст C4, организацию с допустимым названием, набор полей, приглашение и положительную версию условий и хэширует текст в том виде, в каком он показан с этим названием. Выдачи и отзывы не выводят в печать и логи субъекта, организацию, название или поля. Набор полей каноничен при любом порядке входа и отклоняет пустой, повторный, неизвестный набор и больше четырех полей. `RestoreConsentRecord` отклоняет то же, что отклоняет база, а запись в выводе и логах показывает только ID, цель и состояние. - `internal/adapter/secondary/postgres/` (`consents_test.go`): ошибки ограничений журнала превращаются в sentinel-ошибки по SQLSTATE и имени ограничения без деталей строки, ограничивающий ключ согласий в очистке превращается в `ErrTransactionConflict`, неверный вход отклоняется до запросов, каждый сгенерированный тип строки приводится к одной структуре записи, а сохраняемый набор полей идет в порядке, который принимает база. +- `internal/usecase/consent/` (`service_test.go`, с in-memory репозиторием текстов, журналом, transactor и управляемыми часами): выдача C1, C2, C3 и C5 записывает актуальную версию и хэш текста, источник своей точки входа (`GrantAtRegistration` фиксирует C1 и `registration`, `GrantInSettings` фиксирует `consent_settings`) и время внедренных часов, но не любое другое время; выдача со старой, неизвестной или запланированной версией завершается `ErrStaleConsentText`, называет актуальную версию и не доходит до журнала; выдача версии один, публикация версии два и повтор версии один дают устаревшую версию и одну запись; `CheckTextVersion` возвращает актуальный текст, завершается устаревшей версией для старой, неизвестной и запланированной версии, отклоняет неизвестную цель и неверную версию и никогда не обращается к журналу; C4 на общем пути завершается `ErrScopedConsentRequired` до чтения любого репозитория; неверная или пустая версия, неизвестная цель и нулевой субъект отклоняются; повтор возвращает существующую запись с `Created` false и ее первым временем, а в журнале остается одна запись; ошибки репозиториев (нет опубликованного текста, неизвестный субъект) сохраняют свой sentinel, а отсутствие текста не выдается за устаревшую версию; у субъекта, не давшего C3, остальные цели имеют собственные записи, а записи C3 нет; `GrantContact` записывает scope, источник `invitation_acceptance` и хэш показанного текста, возвращает существующую запись при повторе, сообщает, что приглашение занято другим субъектом, и отклоняет устаревшую версию C4, название с пробелами по краям и отсутствие полей, организации, приглашения, субъекта или версии условий; `GrantInSettingsInNewTransaction` повторяет конфликт транзакции после паузы, останавливается после трех попыток, не повторяет другую ошибку и отмененный контекст и откатывает устаревшую выдачу; `NewService` паникует при нулевом transactor или часах. - `internal/adapter/primary/http/` (`router_test.go`): `ListMyConsents` с сессией после валидации отвечает 501, а на неизвестное состояние, limit больше 100 и неверный cursor - 400 с указателем на параметр запроса; при `DenyAllSecurity` отвечает 401 с cookie, без нее и с параметром `subject_id`; DTO не содержат хэша, субъекта или контактов, параметры - только состояние и страница, а пример контракта декодируется и проходит валидацию. - `frontend/src/shared/api/consent-contract.test.ts`: сгенерированные Zod-схемы принимают запись C4 со scope и отозванную запись без scope, отклоняют неизвестную цель, состояние или источник, пустую или неверную версию, пустой или слишком большой набор полей, неизвестный вид контакта и версию условий меньше 1, требуют каждое nullable-поле и отбрасывают хэш или субъекта; операция принимает только состояние и параметры страницы. @@ -248,7 +249,17 @@ Unit-тесты (`make -C backend test`) проверяют правила жу - Двадцать раундов гонки выдачи и отзыва не дают ошибок, кроме `ErrTransactionConflict`, и никогда не оставляют больше одной неотозванной записи версии. - Когда заблокирована только строка согласия устаревшего аккаунта, очистка в сессии с lock timeout 200 ms пропускает аккаунт без ожидания и удаляет его после снятия блокировки. -`TestPostgresMigrations` откатывает миграцию 00009 вместе с остальными и проверяет, что таблиц и функций не осталось. Интеграционные тесты identity, доставки и квот почты называют `consent_records` в своем TRUNCATE таблицы `users`. Набор не покрывает usecase выдачи и отзыва и HTTP-обработчик, а гонку очистки с SQLSTATE 23001 покрывает только unit-тест ее преобразования, потому что ее окно нельзя воспроизвести детерминированно. +`TestConsentGrants` в `backend/integration_test/consent_usecase_test.go` запускает usecase на базе bootstrap с фиксированными часами приложения, вторым текстом C1 и текстом C5, запланированным после часов: + +- Регистрация: `UserRepository.Create` и `GrantAtRegistration` для C1 выполняются в одной транзакции `Transactor` без сессии (таблица сессий остается пустой) и фиксируют один аккаунт и одно C1 со временем приложения и актуальной версией текста. C2 и C5 следуют отдельными операциями, у каждой своя активная запись; C3 не дано, записи C3 нет, пока остальные действуют; C3, выданное позже и отозванное, оставляет C1, C2 и C5 активными. +- Атомарность: транзакция, упавшая после записи аккаунта и C1, не оставляет ни того, ни другого, а выдача для субъекта без аккаунта завершается `ErrUserNotFound` и ничего не записывает. +- Идемпотентность и версии: повтор в собственной транзакции и в бизнес-транзакции возвращает первую запись и ее время и не добавляет строк, а бизнес-транзакция не прерывается. Устаревшая версия C1, запланированная версия C5 и неизвестная версия C3 завершаются ошибкой устаревшей версии с названием актуальной и ничего не записывают; актуальная версия C1 проходит, а устаревшая остается отклоненной. Выдача после отзыва - новая строка. Восемь одновременных повторов создают ровно одну строку. +- Повторная публикация: после выдачи версии один C3 и публикации версии два повтор версии один считается устаревшим, называет версию два и оставляет одну строку и первую запись как текущее C3. +- Повторная регистрация: `UpdateRegistration` и затем `GrantAtRegistration` в одной транзакции возвращают `created` true с новой записью и оставляют ровно одно C1. Обратный порядок показан как риск: выдача находит C1 прежнего регистранта и возвращает его с `created` false, затем обновление удаляет его, и аккаунт остается без C1. +- C4: общий путь отклоняет его и ничего не записывает; `GrantContact` в транзакции сохраняет организацию, название, поля, приглашение и источник `invitation_acceptance`; повтор возвращает ту же запись, устаревшая версия C4 отклоняется, а C4 не создает C2. +- Перезапуск: после закрытия pool новый pool, хранилище и usecase перечисляют те же четыре записи по порядку с их состояниями, отметкой и источником отзыва и исходными временами выдачи, а повторная выдача через новый экземпляр ничего не записывает. + +`TestPostgresMigrations` откатывает миграцию 00009 вместе с остальными и проверяет, что таблиц и функций не осталось. Интеграционные тесты identity, доставки и квот почты называют `consent_records` в своем TRUNCATE таблицы `users`. Набор не покрывает usecase отзыва, HTTP-обработчик и вызов usecase согласий из регистрации и принятия приглашения, а гонку очистки с SQLSTATE 23001 покрывает только unit-тест ее преобразования, потому что ее окно нельзя воспроизвести детерминированно. ## Будущая программная валидация