Files

385 lines
16 KiB
Go

// 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
// 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.
//
// 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 (
"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 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,
registrationVersion int64,
version domain.ConsentTextVersion,
) (GrantResult, error) {
result, err := service.grant(ctx, repositories, grantRequest{
subjectID: subjectID,
purpose: domain.ConsentPurposePersonalData,
version: version,
source: domain.ConsentSourceRegistration,
registrationVersion: registrationVersion,
})
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
registrationVersion int64
}
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,
RegistrationVersion: request.registrationVersion,
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, 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:
}
}
}