feat(accounts): add consent settings and organization management

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 13:00:39 +03:00
1 parent 24638d46d2
commit 391af7a1ef
83 files changed
+10198 -613

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
package consent
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// QueryService reads published consent texts and the current account's ledger.
// The repository is a PostgreSQL adapter outside a transaction; history reads
// always receive the subject ID selected by the authenticated HTTP boundary.
type QueryService struct {
repositories outbound.ConsentRepositories
clock func() time.Time
}
func NewQueryService(repositories outbound.ConsentRepositories, clock func() time.Time) *QueryService {
if repositories == nil {
panic("consent.NewQueryService - repositories must not be nil")
}
if clock == nil {
panic("consent.NewQueryService - clock must not be nil")
}
return &QueryService{repositories: repositories, clock: clock}
}
func (service *QueryService) CurrentText(ctx context.Context, purpose domain.ConsentPurpose) (domain.ConsentText, error) {
if _, err := domain.ParseConsentPurpose(string(purpose)); err != nil {
return domain.ConsentText{}, fmt.Errorf("QueryService.CurrentText - validate purpose: %w", err)
}
if purpose.OrganizationScoped() {
return domain.ConsentText{}, fmt.Errorf("QueryService.CurrentText - c4 text requires an organization snapshot: %w", ErrScopedConsentRequired)
}
text, err := service.repositories.ConsentTexts().Current(ctx, purpose, service.clock())
if err != nil {
return domain.ConsentText{}, fmt.Errorf("QueryService.CurrentText - read current text: %w", err)
}
return text, nil
}
func (service *QueryService) List(ctx context.Context, query outbound.ConsentListQuery) (outbound.ConsentPage, error) {
if query.SubjectID == uuid.Nil {
return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - subject is required: %w", domain.ErrInvalidConsent)
}
if query.Limit < 1 || query.Limit > outbound.MaxConsentPageSize {
return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - limit is out of range: %w", domain.ErrInvalidConsent)
}
if query.State != "" {
if _, err := domain.ParseConsentState(string(query.State)); err != nil {
return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - validate state: %w", err)
}
}
if query.After != nil && (query.After.ID == uuid.Nil || query.After.GrantedAt.IsZero()) {
return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - cursor position is invalid: %w", domain.ErrInvalidConsent)
}
page, err := service.repositories.ConsentLedger().List(ctx, query)
if err != nil {
return outbound.ConsentPage{}, fmt.Errorf("QueryService.List - read ledger: %w", err)
}
return page, nil
}
// HasCurrentConsent is the fail-closed check used by consumers that must not
// proceed without a current grant. A missing record is a denial; a storage
// failure is returned so the caller must also deny instead of assuming consent.
func (service *QueryService) HasCurrentConsent(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (bool, error) {
if subjectID == uuid.Nil {
return false, fmt.Errorf("QueryService.HasCurrentConsent - subject is required: %w", domain.ErrInvalidConsent)
}
if purpose.OrganizationScoped() {
return false, fmt.Errorf("QueryService.HasCurrentConsent - c4 needs an organization scope: %w", domain.ErrInvalidConsent)
}
if _, err := domain.ParseConsentPurpose(string(purpose)); err != nil {
return false, fmt.Errorf("QueryService.HasCurrentConsent - validate purpose: %w", err)
}
_, err := service.repositories.ConsentLedger().Current(ctx, subjectID, purpose)
if errors.Is(err, outbound.ErrConsentNotFound) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("QueryService.HasCurrentConsent - read current consent: %w", err)
}
return true, nil
}
@@ -0,0 +1,126 @@
package consent
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func TestQueryServiceReadsCurrentTextAndOwnLedgerPosition(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
body := "Current c2 text."
hash := domain.HashConsentText(body)
text, err := domain.RestoreConsentText(domain.StoredConsentText{
Purpose: string(domain.ConsentPurposePublication), Version: "c2-current", Body: body,
Hash: hash[:], Kind: string(domain.ConsentTextKindDemo), PublishedAt: now.Add(-time.Hour),
})
if err != nil {
t.Fatal(err)
}
accountID := uuid.New()
position := outbound.ConsentListPosition{GrantedAt: now.Add(-time.Minute), ID: uuid.New()}
ledger := &queryTestLedger{current: domain.ConsentRecord{}, page: outbound.ConsentPage{HasMore: true}}
reader := NewQueryService(&queryTestRepositories{
texts: queryTestTexts{text: text},
ledger: ledger,
}, func() time.Time { return now })
gotText, err := reader.CurrentText(context.Background(), domain.ConsentPurposePublication)
if err != nil || gotText.Version() != text.Version() || gotText.Body() != body {
t.Fatalf("CurrentText() = %#v, %v", gotText, err)
}
query := outbound.ConsentListQuery{
SubjectID: accountID, State: domain.ConsentStateActive,
After: &position, Limit: 25,
}
page, err := reader.List(context.Background(), query)
if err != nil || !page.HasMore {
t.Fatalf("List() = %#v, %v", page, err)
}
if ledger.listQuery.SubjectID != accountID || ledger.listQuery.State != query.State ||
ledger.listQuery.After == nil || *ledger.listQuery.After != position || ledger.listQuery.Limit != 25 {
t.Fatalf("List query = %#v", ledger.listQuery)
}
}
func TestQueryServiceHasCurrentConsentFailsClosed(t *testing.T) {
accountID := uuid.New()
for _, test := range []struct {
name string
current error
want bool
wantErr bool
}{
{name: "missing grant denies", current: outbound.ErrConsentNotFound},
{name: "current grant allows", want: true},
{name: "storage failure denies", current: errors.New("storage unavailable"), wantErr: true},
} {
t.Run(test.name, func(t *testing.T) {
ledger := &queryTestLedger{currentErr: test.current}
reader := NewQueryService(&queryTestRepositories{ledger: ledger}, time.Now)
allowed, err := reader.HasCurrentConsent(context.Background(), accountID, domain.ConsentPurposeFSPImport)
if allowed != test.want || (err != nil) != test.wantErr {
t.Fatalf("HasCurrentConsent() = %v, %v", allowed, err)
}
})
}
}
func TestQueryServiceRejectsC4TextWithoutOrganizationSnapshot(t *testing.T) {
reader := NewQueryService(&queryTestRepositories{}, time.Now)
if _, err := reader.CurrentText(context.Background(), domain.ConsentPurposeContactDisclosure); !errors.Is(err, ErrScopedConsentRequired) {
t.Fatalf("CurrentText(c4) error = %v, want ErrScopedConsentRequired", err)
}
}
type queryTestRepositories struct {
outbound.ConsentRepositories
texts outbound.ConsentTextRepository
ledger outbound.ConsentLedger
}
func (repositories *queryTestRepositories) ConsentTexts() outbound.ConsentTextRepository {
return repositories.texts
}
func (repositories *queryTestRepositories) ConsentLedger() outbound.ConsentLedger {
return repositories.ledger
}
type queryTestTexts struct {
outbound.ConsentTextRepository
text domain.ConsentText
}
func (texts queryTestTexts) Current(context.Context, domain.ConsentPurpose, time.Time) (domain.ConsentText, error) {
return texts.text, nil
}
type queryTestLedger struct {
outbound.ConsentLedger
currentErr error
current domain.ConsentRecord
listQuery outbound.ConsentListQuery
page outbound.ConsentPage
}
func (ledger *queryTestLedger) Current(context.Context, uuid.UUID, domain.ConsentPurpose) (domain.ConsentRecord, error) {
if ledger.currentErr != nil {
return domain.ConsentRecord{}, ledger.currentErr
}
return ledger.current, nil
}
func (ledger *queryTestLedger) List(_ context.Context, query outbound.ConsentListQuery) (outbound.ConsentPage, error) {
ledger.listQuery = query
return ledger.page, nil
}
+135
View File
@@ -0,0 +1,135 @@
package consent
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
type SettingsRevocationInput struct {
SubjectID uuid.UUID
Purpose domain.ConsentPurpose
OrganizationID uuid.UUID
}
type RevocationResult struct {
Records []domain.ConsentRecord
}
func (service *Service) RevokeInSettingsInNewTransaction(ctx context.Context, input SettingsRevocationInput) (RevocationResult, error) {
const location = "Service.RevokeInSettingsInNewTransaction"
if input.Purpose == domain.ConsentPurposePersonalData {
return RevocationResult{}, fmt.Errorf("%s - c1 uses the account deletion request: %w", location, domain.ErrInvalidConsent)
}
if input.Purpose == domain.ConsentPurposeContactDisclosure && input.OrganizationID == uuid.Nil {
return RevocationResult{}, fmt.Errorf("%s - c4 organization is required: %w", location, domain.ErrInvalidConsent)
}
if input.Purpose != domain.ConsentPurposeContactDisclosure && input.OrganizationID != uuid.Nil {
return RevocationResult{}, fmt.Errorf("%s - organization scope is only valid for c4: %w", location, domain.ErrInvalidConsent)
}
if _, err := domain.ParseConsentPurpose(string(input.Purpose)); err != nil {
return RevocationResult{}, fmt.Errorf("%s - validate purpose: %w", location, err)
}
revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{
SubjectID: input.SubjectID, Purpose: input.Purpose, OrganizationID: input.OrganizationID,
Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: service.clock(),
})
if err != nil {
return RevocationResult{}, fmt.Errorf("%s - create revocation: %w", location, err)
}
var result RevocationResult
err = service.inNewTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
records, err := unit.ConsentLedger().Revoke(ctx, revocation)
if err != nil {
return fmt.Errorf("%s - revoke consent ledger: %w", location, err)
}
if len(records) == 0 {
result = RevocationResult{}
return nil
}
if err := unit.ConsentRevocationEffects().Apply(ctx, revocation, records); err != nil {
return fmt.Errorf("%s - apply revocation effects: %w", location, err)
}
result = RevocationResult{Records: records}
return nil
})
if err != nil {
return RevocationResult{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
func (service *Service) RequestAccountDeletionInNewTransaction(ctx context.Context, subjectID uuid.UUID) (domain.AccountDeletionRequest, error) {
const location = "Service.RequestAccountDeletionInNewTransaction"
request, err := domain.NewAccountDeletionRequest(subjectID, service.clock())
if err != nil {
return domain.AccountDeletionRequest{}, fmt.Errorf("%s - create request: %w", location, err)
}
revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{
SubjectID: subjectID, Purpose: domain.ConsentPurposePersonalData,
Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: request.RequestedAt(),
})
if err != nil {
return domain.AccountDeletionRequest{}, fmt.Errorf("%s - create c1 revocation: %w", location, err)
}
var result domain.AccountDeletionRequest
err = service.inNewTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
storedRequest, created, err := unit.AccountDeletionRequests().CreateOrGet(ctx, request)
if err != nil {
return fmt.Errorf("%s - store account deletion request: %w", location, err)
}
records, err := unit.ConsentLedger().Revoke(ctx, revocation)
if err != nil {
return fmt.Errorf("%s - revoke c1 consent: %w", location, err)
}
if len(records) > 0 {
if err := unit.ConsentRevocationEffects().Apply(ctx, revocation, records); err != nil {
return fmt.Errorf("%s - apply c1 revocation effects: %w", location, err)
}
}
if created {
if err := appendDeletionRequestedEvent(ctx, unit, storedRequest); err != nil {
return fmt.Errorf("%s - append deletion request event: %w", location, err)
}
}
result = storedRequest
return nil
})
if err != nil {
return domain.AccountDeletionRequest{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
type accountDeletionRequestedPayload struct {
RequestID uuid.UUID `json:"request_id"`
SubjectID uuid.UUID `json:"subject_id"`
RequestedAt time.Time `json:"requested_at"`
}
func appendDeletionRequestedEvent(ctx context.Context, unit outbound.UnitOfWork, request domain.AccountDeletionRequest) error {
const location = "appendDeletionRequestedEvent"
body, err := json.Marshal(accountDeletionRequestedPayload{
RequestID: request.ID(), SubjectID: request.SubjectID(), RequestedAt: request.RequestedAt(),
})
if err != nil {
return fmt.Errorf("%s - marshal payload: %w", location, err)
}
event, err := domain.NewDomainEvent(domain.DomainEventInput{
EventType: "privacy.account_deletion_requested", SchemaVersion: 1,
AggregateType: "account_deletion_request", AggregateID: request.ID(), AggregateVersion: 1, Payload: body,
})
if err != nil {
return fmt.Errorf("%s - build event: %w", location, err)
}
if err := unit.Outbox().Append(ctx, event); err != nil {
return fmt.Errorf("%s - append event: %w", location, err)
}
return nil
}
@@ -0,0 +1,501 @@
package consent
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func TestSettingsRevocationAppliesEffectsOnce(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
subject := uuid.New()
ledger := &revocationTestLedger{records: []domain.ConsentRecord{
revocationTestRecord(t, subject, domain.ConsentPurposePublication, uuid.Nil, now.Add(-time.Hour)),
}}
harness := newRevocationTestService(now, ledger)
input := SettingsRevocationInput{SubjectID: subject, Purpose: domain.ConsentPurposePublication}
first, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), input)
if err != nil || len(first.Records) != 1 || first.Records[0].State() != domain.ConsentStateRevoked {
t.Fatalf("first revoke = %#v, %v; want one revoked record", first, err)
}
if len(harness.effects.calls) != 1 || harness.effects.calls[0].SubjectID() != subject {
t.Fatalf("revocation effects = %v; want one effect for the caller", harness.effects.calls)
}
second, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), input)
if err != nil || len(second.Records) != 0 {
t.Fatalf("repeat revoke = %#v, %v; want no changed records", second, err)
}
if len(harness.effects.calls) != 1 {
t.Fatalf("repeat revoke applied effects again: %d calls", len(harness.effects.calls))
}
}
func TestDownstreamGrantClosureIsRecordBoundAcrossRegrant(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
for _, purpose := range []domain.ConsentPurpose{domain.ConsentPurposePublication, domain.ConsentPurposeContactDisclosure} {
t.Run(string(purpose), func(t *testing.T) {
subject := uuid.New()
organization := uuid.Nil
if purpose.OrganizationScoped() {
organization = uuid.New()
}
oldRecord := revocationTestRecord(t, subject, purpose, organization, now.Add(-time.Hour))
ledger := &revocationTestLedger{records: []domain.ConsentRecord{oldRecord}}
harness := newRevocationTestService(now, ledger)
text := revocationTestConsentText(t, purpose, now.Add(-time.Minute))
harness.transactor.unit.texts = revocationTestTexts{text: text}
harness.effects.activeDownstreamGrants = map[uuid.UUID]bool{oldRecord.ID(): true}
_, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), SettingsRevocationInput{
SubjectID: subject, Purpose: purpose, OrganizationID: organization,
})
if err != nil {
t.Fatalf("revoke %s: %v", purpose, err)
}
if harness.effects.activeDownstreamGrants[oldRecord.ID()] || !harness.effects.closedConsentRecords[oldRecord.ID()] {
t.Fatalf("revocation did not synchronously close downstream grant for consent record %s", oldRecord.ID())
}
var newRecord domain.ConsentRecord
if purpose == domain.ConsentPurposeContactDisclosure {
fields, err := domain.NewContactFieldSet(domain.ContactFieldPhone)
if err != nil {
t.Fatal(err)
}
grant, err := harness.service.GrantContact(context.Background(), harness.transactor.unit, ContactGrantInput{
SubjectID: subject, OrganizationID: organization, OrganizationName: "Acme Synthetic LLC", Fields: fields,
InvitationID: uuid.New(), InvitationTermsVersion: 1, TextVersion: text.Version(),
})
if err != nil || !grant.Created {
t.Fatalf("grant new C4 invitation = %#v, %v", grant, err)
}
newRecord = grant.Record
} else {
grant, err := harness.service.GrantInSettingsInNewTransaction(context.Background(), SettingsGrantInput{
SubjectID: subject, Purpose: purpose, TextVersion: text.Version(),
})
if err != nil || !grant.Created {
t.Fatalf("grant new C2 version = %#v, %v", grant, err)
}
newRecord = grant.Record
}
if newRecord.ID() == oldRecord.ID() || newRecord.State() != domain.ConsentStateActive {
t.Fatalf("new consent record = %s/%s, want a distinct active record", newRecord.ID(), newRecord.State())
}
if harness.effects.closedConsentRecords[newRecord.ID()] || harness.effects.activeDownstreamGrants[oldRecord.ID()] {
t.Fatalf("new consent reopened the old downstream grant: old=%s new=%s", oldRecord.ID(), newRecord.ID())
}
if !harness.effects.tryOpenForCurrentConsent(context.Background(), newRecord, ledger) ||
!harness.effects.activeDownstreamGrants[newRecord.ID()] {
t.Fatal("test adapter did not open a downstream grant for the new current consent record")
}
if harness.effects.tryOpenForCurrentConsent(context.Background(), oldRecord, ledger) {
t.Fatal("test adapter reopened a grant bound to the revoked consent record")
}
})
}
}
func TestContactRevocationStaysWithinStoredOrganizationScope(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
subject := uuid.New()
organization := uuid.New()
otherOrganization := uuid.New()
ledger := &revocationTestLedger{records: []domain.ConsentRecord{
revocationTestRecord(t, subject, domain.ConsentPurposeContactDisclosure, organization, now.Add(-time.Hour)),
revocationTestRecord(t, subject, domain.ConsentPurposeContactDisclosure, otherOrganization, now.Add(-30*time.Minute)),
}}
harness := newRevocationTestService(now, ledger)
result, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), SettingsRevocationInput{
SubjectID: subject, Purpose: domain.ConsentPurposeContactDisclosure, OrganizationID: organization,
})
if err != nil || len(result.Records) != 1 || result.Records[0].OrganizationID() != organization {
t.Fatalf("scoped revoke = %#v, %v; want only organization %s", result, err, organization)
}
if len(harness.effects.records) != 1 || harness.effects.records[0].OrganizationID() != organization ||
harness.effects.records[0].Fields().Fields()[0] != domain.ContactFieldPhone {
t.Fatalf("revocation effect records = %v; want stored organization and field scope", harness.effects.records)
}
if ledger.records[1].State() != domain.ConsentStateActive {
t.Fatalf("record for another organization changed to %s", ledger.records[1].State())
}
}
func TestAccountDeletionRequestIsDurableAndIdempotent(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
subject := uuid.New()
ledger := &revocationTestLedger{records: []domain.ConsentRecord{
revocationTestRecord(t, subject, domain.ConsentPurposePersonalData, uuid.Nil, now.Add(-time.Hour)),
}}
harness := newRevocationTestService(now, ledger)
first, err := harness.service.RequestAccountDeletionInNewTransaction(context.Background(), subject)
if err != nil || first.IsZero() || first.SubjectID() != subject {
t.Fatalf("first deletion request = %#v, %v", first, err)
}
if len(harness.deletions.requests) != 1 || len(harness.outbox.events) != 1 ||
harness.outbox.events[0].EventType() != "privacy.account_deletion_requested" {
t.Fatalf("request/outbox counts = %d/%d; want one durable request and one event", len(harness.deletions.requests), len(harness.outbox.events))
}
if ledger.records[0].State() != domain.ConsentStateRevoked || len(harness.effects.calls) != 1 {
t.Fatalf("C1 revocation = %s, effects=%d; want revoked with one intent", ledger.records[0].State(), len(harness.effects.calls))
}
second, err := harness.service.RequestAccountDeletionInNewTransaction(context.Background(), subject)
if err != nil || second.ID() != first.ID() {
t.Fatalf("repeat deletion request = %#v, %v; want same durable request", second, err)
}
if len(harness.deletions.requests) != 1 || len(harness.outbox.events) != 1 || len(harness.effects.calls) != 1 {
t.Fatalf("repeat request duplicated effects: requests=%d events=%d revocations=%d",
len(harness.deletions.requests), len(harness.outbox.events), len(harness.effects.calls))
}
}
func TestRevocationFailureReturnsToTheTransactionBoundary(t *testing.T) {
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
subject := uuid.New()
ledger := &revocationTestLedger{records: []domain.ConsentRecord{
revocationTestRecord(t, subject, domain.ConsentPurposeFSPImport, uuid.Nil, now.Add(-time.Hour)),
}}
harness := newRevocationTestService(now, ledger)
harness.effects.err = errors.New("outbox unavailable")
_, err := harness.service.RevokeInSettingsInNewTransaction(context.Background(), SettingsRevocationInput{
SubjectID: subject, Purpose: domain.ConsentPurposeFSPImport,
})
if err == nil || !errors.Is(harness.transactor.lastErr, harness.effects.err) {
t.Fatalf("revoke error = %v, transaction error = %v; want the effect failure", err, harness.transactor.lastErr)
}
}
type revocationTestHarness struct {
service *Service
transactor *revocationTestTransactor
deletions *revocationTestDeletions
effects *revocationTestEffects
outbox *revocationTestOutbox
}
func newRevocationTestService(now time.Time, ledger *revocationTestLedger) *revocationTestHarness {
harness := &revocationTestHarness{
deletions: &revocationTestDeletions{}, effects: &revocationTestEffects{}, outbox: &revocationTestOutbox{},
}
unit := &revocationTestUnit{
ledger: ledger, deletions: harness.deletions, effects: harness.effects, outbox: harness.outbox,
}
harness.transactor = &revocationTestTransactor{unit: unit}
harness.service = NewService(harness.transactor, func() time.Time { return now })
return harness
}
func revocationTestConsentText(t *testing.T, purpose domain.ConsentPurpose, publishedAt time.Time) domain.ConsentText {
t.Helper()
body := "I consent to this test purpose."
if purpose == domain.ConsentPurposeContactDisclosure {
body = "I consent to share selected contacts with {organization}."
}
hash := domain.HashConsentText(body)
text, err := domain.RestoreConsentText(domain.StoredConsentText{
Purpose: string(purpose), Version: string(purpose) + "-2026-10-01", Body: body,
Hash: hash[:], Kind: string(domain.ConsentTextKindDemo), PublishedAt: publishedAt,
})
if err != nil {
t.Fatalf("RestoreConsentText() error = %v", err)
}
return text
}
func revocationTestRecord(t *testing.T, subject uuid.UUID, purpose domain.ConsentPurpose, organization uuid.UUID, grantedAt time.Time) domain.ConsentRecord {
t.Helper()
version := domain.ConsentTextVersion(string(purpose) + "-2026-10-01")
hash := domain.HashConsentText("consent text")
source := domain.ConsentSourceConsentSettings
if purpose == domain.ConsentPurposeContactDisclosure {
source = domain.ConsentSourceInvitationAcceptance
}
stored := domain.StoredConsentRecord{
ID: uuid.New(), SubjectID: subject, Purpose: string(purpose), TextVersion: string(version), TextHash: hash[:],
Source: string(source), State: string(domain.ConsentStateActive), GrantedAt: grantedAt,
}
if purpose == domain.ConsentPurposeContactDisclosure {
fields, err := domain.NewContactFieldSet(domain.ContactFieldPhone)
if err != nil {
t.Fatal(err)
}
stored.OrganizationID = organization
stored.OrganizationName = "Acme Synthetic LLC"
stored.FieldSet = contactFieldCodes(fields.Fields())
stored.InvitationID = uuid.New()
stored.InvitationTermsVersion = 1
}
record, err := domain.RestoreConsentRecord(stored)
if err != nil {
t.Fatalf("RestoreConsentRecord() error = %v", err)
}
return record
}
type revocationTestLedger struct {
outbound.ConsentLedger
records []domain.ConsentRecord
}
type revocationTestTexts struct {
outbound.ConsentTextRepository
text domain.ConsentText
}
func (texts revocationTestTexts) Current(_ context.Context, purpose domain.ConsentPurpose, _ time.Time) (domain.ConsentText, error) {
if texts.text.IsZero() || texts.text.Purpose() != purpose {
return domain.ConsentText{}, outbound.ErrConsentTextNotFound
}
return texts.text, nil
}
func (ledger *revocationTestLedger) Grant(_ context.Context, grant domain.ConsentGrant) (domain.ConsentRecord, bool, error) {
for _, existing := range ledger.records {
if existing.SubjectID() == grant.SubjectID() && existing.Purpose() == grant.Purpose() &&
existing.TextVersion() == grant.TextVersion() && existing.State() != domain.ConsentStateRevoked {
return existing, false, nil
}
}
hash := grant.TextHash()
record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{
ID: grant.ID(), SubjectID: grant.SubjectID(), Purpose: string(grant.Purpose()),
TextVersion: string(grant.TextVersion()), TextHash: hash[:], Source: string(grant.Source()),
RegistrationVersion: grant.RegistrationVersion(), State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(),
})
if err != nil {
return domain.ConsentRecord{}, false, err
}
ledger.records = append(ledger.records, record)
return record, true, nil
}
func (ledger *revocationTestLedger) GrantContact(_ context.Context, grant domain.ContactConsentGrant) (domain.ConsentRecord, bool, error) {
for _, existing := range ledger.records {
if existing.InvitationID() == grant.InvitationID() {
if existing.SubjectID() != grant.SubjectID() {
return domain.ConsentRecord{}, false, outbound.ErrConsentInvitationTaken
}
return existing, false, nil
}
}
hash := grant.TextHash()
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: contactFieldCodes(grant.Fields().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 *revocationTestLedger) Current(_ context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error) {
var current domain.ConsentRecord
for _, record := range ledger.records {
if record.SubjectID() != subjectID || record.Purpose() != purpose || record.State() == domain.ConsentStateRevoked {
continue
}
if current.IsZero() || record.GrantedAt().After(current.GrantedAt()) ||
(record.GrantedAt().Equal(current.GrantedAt()) && record.ID().String() > current.ID().String()) {
current = record
}
}
if current.IsZero() {
return domain.ConsentRecord{}, outbound.ErrConsentNotFound
}
return current, nil
}
func (ledger *revocationTestLedger) CurrentContact(_ context.Context, subjectID, organizationID uuid.UUID) ([]domain.ConsentRecord, error) {
var current []domain.ConsentRecord
for _, record := range ledger.records {
if record.SubjectID() == subjectID && record.Purpose() == domain.ConsentPurposeContactDisclosure &&
record.OrganizationID() == organizationID && record.State() != domain.ConsentStateRevoked {
current = append(current, record)
}
}
return current, nil
}
func (ledger *revocationTestLedger) Revoke(_ context.Context, revocation domain.ConsentRevocation) ([]domain.ConsentRecord, error) {
var revoked []domain.ConsentRecord
for index, record := range ledger.records {
if record.SubjectID() != revocation.SubjectID() || record.Purpose() != revocation.Purpose() ||
record.State() == domain.ConsentStateRevoked ||
(revocation.Purpose().OrganizationScoped() && record.OrganizationID() != revocation.OrganizationID()) {
continue
}
revokedAt := revocation.RevokedAt()
if revokedAt.Before(record.GrantedAt()) {
revokedAt = record.GrantedAt()
}
hash := record.TextHash()
var contactFields []string
if revocation.Purpose().OrganizationScoped() {
contactFields = contactFieldCodes(record.Fields().Fields())
}
stored := domain.StoredConsentRecord{
ID: record.ID(), SubjectID: record.SubjectID(), Purpose: string(record.Purpose()),
TextVersion: string(record.TextVersion()), TextHash: hash[:], Source: string(record.Source()),
RegistrationVersion: record.RegistrationVersion(), State: string(domain.ConsentStateRevoked), GrantedAt: record.GrantedAt(),
RevokedAt: &revokedAt, RevocationSource: string(revocation.Source()), OrganizationID: record.OrganizationID(),
OrganizationName: record.OrganizationName(), FieldSet: contactFields, InvitationID: record.InvitationID(),
InvitationTermsVersion: record.InvitationTermsVersion(),
}
updated, err := domain.RestoreConsentRecord(stored)
if err != nil {
return nil, err
}
ledger.records[index] = updated
revoked = append(revoked, updated)
}
return revoked, nil
}
func contactFieldCodes(fields []domain.ContactField) []string {
codes := make([]string, 0, len(fields))
for _, field := range fields {
codes = append(codes, string(field))
}
return codes
}
type revocationTestDeletions struct {
outbound.AccountDeletionRequests
requests []domain.AccountDeletionRequest
}
func (repository *revocationTestDeletions) CreateOrGet(_ context.Context, request domain.AccountDeletionRequest) (domain.AccountDeletionRequest, bool, error) {
for _, existing := range repository.requests {
if existing.SubjectID() == request.SubjectID() {
return existing, false, nil
}
}
repository.requests = append(repository.requests, request)
return request, true, nil
}
type revocationTestEffects struct {
outbound.ConsentRevocationEffects
calls []domain.ConsentRevocation
records []domain.ConsentRecord
activeDownstreamGrants map[uuid.UUID]bool
closedConsentRecords map[uuid.UUID]bool
err error
}
func (effects *revocationTestEffects) Apply(_ context.Context, revocation domain.ConsentRevocation, records []domain.ConsentRecord) error {
if effects.err != nil {
return effects.err
}
effects.calls = append(effects.calls, revocation)
effects.records = append(effects.records, records...)
if effects.activeDownstreamGrants == nil {
effects.activeDownstreamGrants = make(map[uuid.UUID]bool)
}
if effects.closedConsentRecords == nil {
effects.closedConsentRecords = make(map[uuid.UUID]bool)
}
for _, record := range records {
effects.activeDownstreamGrants[record.ID()] = false
effects.closedConsentRecords[record.ID()] = true
}
return nil
}
func (effects *revocationTestEffects) tryOpenForCurrentConsent(
ctx context.Context,
record domain.ConsentRecord,
ledger outbound.ConsentLedger,
) bool {
if record.IsZero() || effects.closedConsentRecords[record.ID()] {
return false
}
if record.Purpose().OrganizationScoped() {
current, err := ledger.CurrentContact(ctx, record.SubjectID(), record.OrganizationID())
if err != nil {
return false
}
for _, candidate := range current {
if candidate.ID() == record.ID() {
effects.activeDownstreamGrants[record.ID()] = true
return true
}
}
return false
}
current, err := ledger.Current(ctx, record.SubjectID(), record.Purpose())
if err != nil || current.ID() != record.ID() {
return false
}
if effects.activeDownstreamGrants == nil {
effects.activeDownstreamGrants = make(map[uuid.UUID]bool)
}
effects.activeDownstreamGrants[record.ID()] = true
return true
}
type revocationTestOutbox struct {
outbound.OutboxWriter
events []domain.DomainEvent
}
func (outbox *revocationTestOutbox) Append(_ context.Context, events ...domain.DomainEvent) error {
outbox.events = append(outbox.events, events...)
return nil
}
type revocationTestUnit struct {
outbound.UnitOfWork
ledger *revocationTestLedger
texts outbound.ConsentTextRepository
deletions *revocationTestDeletions
effects *revocationTestEffects
outbox *revocationTestOutbox
}
func (unit *revocationTestUnit) ConsentLedger() outbound.ConsentLedger { return unit.ledger }
func (unit *revocationTestUnit) ConsentTexts() outbound.ConsentTextRepository { return unit.texts }
func (unit *revocationTestUnit) AccountDeletionRequests() outbound.AccountDeletionRequests {
return unit.deletions
}
func (unit *revocationTestUnit) ConsentRevocationEffects() outbound.ConsentRevocationEffects {
return unit.effects
}
func (unit *revocationTestUnit) Outbox() outbound.OutboxWriter { return unit.outbox }
type revocationTestTransactor struct {
unit *revocationTestUnit
lastErr error
}
func (transactor *revocationTestTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error {
transactor.lastErr = work(ctx, transactor.unit)
return transactor.lastErr
}
+8 -4
View File
@@ -1,4 +1,4 @@
// Package consent grants the consents C1-C5 of the consent ledger.
// Package consent manages consent grants, revocations, and the C1 deletion request.
//
// 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
@@ -9,9 +9,13 @@
// 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 consent revocation, which calls ConsentLedger().Revoke.
// C1 revocation creates a durable account-deletion request and never deletes
// the account synchronously. Other revocations update the ledger and apply
// transaction-bound effects. C2 closes local publication, C3 leaves the
// manual assessment path available, and C5 denies future import through the
// current-consent gate. Outbox events are notifications rather than access
// checks; external FSP deletion and downstream contact-grant adapters are not
// implemented here.
package consent
import (