feat(consent): add versioned append-only consent ledger C1-C5

This commit is contained in:
shira committed 2026-10-06 14:52:33 +03:00
1 parent 008254e44a
commit de49f93b0b
64 files changed
+9244 -132

No files matched your search

+865
View File
@@ -0,0 +1,865 @@
package domain
import (
"crypto/sha256"
"errors"
"fmt"
"log/slog"
"regexp"
"slices"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
)
var (
// ErrInvalidConsent reports a grant, revocation, or stored record that
// breaks a consent ledger rule.
ErrInvalidConsent = errors.New("invalid consent")
// ErrInvalidConsentText reports a consent text, version, or hash that
// breaks a rule, including a stored text whose hash does not match its
// body.
ErrInvalidConsentText = errors.New("invalid consent text")
)
const (
// ConsentTextHashSize is the size of a SHA-256 digest.
ConsentTextHashSize = sha256.Size
// ConsentTextOrganizationPlaceholder marks where the C4 text names the
// organization. Only the C4 text contains it.
ConsentTextOrganizationPlaceholder = "{organization}"
// maxConsentTextRunes matches the contract bound of ConsentText.text.
maxConsentTextRunes = 100000
// maxOrganizationNameRunes matches InvitationOrganization.name.
maxOrganizationNameRunes = 200
// maxContactFields is the number of ContactField kinds.
maxContactFields = 4
)
// consentTextVersionPattern is the contract pattern of ConsentTextVersion
// with its length bound of 1 to 64 characters.
var consentTextVersionPattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`)
// ConsentPurpose is one of the independent consents C1-C5 of PRD FR01. A
// grant or revocation of one purpose never changes another.
type ConsentPurpose string
const (
// ConsentPurposePersonalData is C1, the processing of personal data,
// given at registration.
ConsentPurposePersonalData ConsentPurpose = "c1"
// ConsentPurposePublication is C2, the publication of the candidate card.
ConsentPurposePublication ConsentPurpose = "c2"
// ConsentPurposeAutoCategorization is C3, the automatic categorization.
ConsentPurposeAutoCategorization ConsentPurpose = "c3"
// ConsentPurposeContactDisclosure is C4, the transfer of selected contact
// data to one organization. It is always scoped; see ContactConsentGrant.
ConsentPurposeContactDisclosure ConsentPurpose = "c4"
// ConsentPurposeFSPImport is C5, the import of FSP results.
ConsentPurposeFSPImport ConsentPurpose = "c5"
)
// ParseConsentPurpose accepts a known purpose.
func ParseConsentPurpose(value string) (ConsentPurpose, error) {
purpose := ConsentPurpose(value)
switch purpose {
case ConsentPurposePersonalData, ConsentPurposePublication, ConsentPurposeAutoCategorization,
ConsentPurposeContactDisclosure, ConsentPurposeFSPImport:
return purpose, nil
default:
return "", fmt.Errorf("domain.ParseConsentPurpose - unknown purpose: %w", ErrInvalidConsent)
}
}
// OrganizationScoped reports whether a grant of the purpose names an
// organization and a contact field set. Only C4 does.
func (purpose ConsentPurpose) OrganizationScoped() bool {
return purpose == ConsentPurposeContactDisclosure
}
// ConsentTextVersion identifies a published consent text, such as
// "c1-2026-10-01".
type ConsentTextVersion string
// ParseConsentTextVersion accepts 1 to 64 characters A-Z, a-z, 0-9, ".",
// "_", and "-".
func ParseConsentTextVersion(value string) (ConsentTextVersion, error) {
if !consentTextVersionPattern.MatchString(value) {
return "", fmt.Errorf("domain.ParseConsentTextVersion - version must have 1 to 64 characters A-Z a-z 0-9 . _ -: %w", ErrInvalidConsentText)
}
return ConsentTextVersion(value), nil
}
// ConsentTextHash is the SHA-256 digest of the UTF-8 bytes of exactly the
// text a subject saw.
type ConsentTextHash [ConsentTextHashSize]byte
// HashConsentText returns the digest of text.
func HashConsentText(text string) ConsentTextHash {
return sha256.Sum256([]byte(text))
}
// ConsentTextHashFromBytes accepts a stored 32-byte digest. An empty, short,
// long, or all-zero value is refused.
func ConsentTextHashFromBytes(value []byte) (ConsentTextHash, error) {
var hash ConsentTextHash
if len(value) != len(hash) {
return hash, fmt.Errorf("domain.ConsentTextHashFromBytes - hash must have %d bytes: %w", ConsentTextHashSize, ErrInvalidConsentText)
}
copy(hash[:], value)
if hash.IsZero() {
return hash, fmt.Errorf("domain.ConsentTextHashFromBytes - hash must not be all zero: %w", ErrInvalidConsentText)
}
return hash, nil
}
// IsZero reports the all-zero value, which marks a missing hash.
func (hash ConsentTextHash) IsZero() bool { return hash == ConsentTextHash{} }
// ConsentTextKind tells a demonstration text from a text of the operator.
type ConsentTextKind string
const (
// ConsentTextKindDemo is a synthetic text for the demonstration on
// synthetic data, without a legal review.
ConsentTextKindDemo ConsentTextKind = "demo"
// ConsentTextKindOperator is a text published by the personal data
// operator, required before real data are accepted (PRD 7.3).
ConsentTextKindOperator ConsentTextKind = "operator"
)
// ConsentText is one immutable published version of the text of a purpose.
type ConsentText struct {
purpose ConsentPurpose
version ConsentTextVersion
body string
hash ConsentTextHash
kind ConsentTextKind
publishedAt time.Time
}
// StoredConsentText carries the columns of a stored text.
type StoredConsentText struct {
Purpose string
Version string
Body string
Hash []byte
Kind string
PublishedAt time.Time
}
// RestoreConsentText validates a stored text, including that its hash is the
// digest of its body, so a row changed outside the application fails with
// ErrInvalidConsentText.
func RestoreConsentText(stored StoredConsentText) (ConsentText, error) {
const location = "domain.RestoreConsentText"
purpose, err := ParseConsentPurpose(stored.Purpose)
if err != nil {
return ConsentText{}, fmt.Errorf("%s - validate purpose: %w", location, err)
}
version, err := ParseConsentTextVersion(stored.Version)
if err != nil {
return ConsentText{}, fmt.Errorf("%s - validate version: %w", location, err)
}
hash, err := ConsentTextHashFromBytes(stored.Hash)
if err != nil {
return ConsentText{}, fmt.Errorf("%s - validate hash: %w", location, err)
}
kind := ConsentTextKind(stored.Kind)
switch {
case stored.Body == "" || !utf8.ValidString(stored.Body) || utf8.RuneCountInString(stored.Body) > maxConsentTextRunes:
return ConsentText{}, fmt.Errorf("%s - body must be valid UTF-8 of 1 to %d characters: %w", location, maxConsentTextRunes, ErrInvalidConsentText)
case HashConsentText(stored.Body) != hash:
return ConsentText{}, fmt.Errorf("%s - hash does not match the body: %w", location, ErrInvalidConsentText)
case purpose.OrganizationScoped() != strings.Contains(stored.Body, ConsentTextOrganizationPlaceholder):
return ConsentText{}, fmt.Errorf("%s - only the C4 text names the organization: %w", location, ErrInvalidConsentText)
case kind != ConsentTextKindDemo && kind != ConsentTextKindOperator:
return ConsentText{}, fmt.Errorf("%s - unknown kind: %w", location, ErrInvalidConsentText)
case stored.PublishedAt.IsZero():
return ConsentText{}, fmt.Errorf("%s - publication time must be set: %w", location, ErrInvalidConsentText)
}
return ConsentText{
purpose: purpose,
version: version,
body: stored.Body,
hash: hash,
kind: kind,
publishedAt: stored.PublishedAt,
}, nil
}
func (text ConsentText) Purpose() ConsentPurpose { return text.purpose }
func (text ConsentText) Version() ConsentTextVersion { return text.version }
func (text ConsentText) Body() string { return text.body }
func (text ConsentText) Kind() ConsentTextKind { return text.kind }
func (text ConsentText) PublishedAt() time.Time { return text.publishedAt }
// Hash is the digest of Body. A grant of C1-C3 or C5 records exactly this
// hash; a C4 grant records the hash of RenderForOrganization instead.
func (text ConsentText) Hash() ConsentTextHash { return text.hash }
// IsZero reports a ConsentText not built by RestoreConsentText.
func (text ConsentText) IsZero() bool { return text.purpose == "" }
// RenderForOrganization returns the C4 text as the candidate sees it: the
// body with every placeholder replaced by the organization name. The C4
// grant records HashConsentText of this result. The name must be one line
// of 1 to 200 characters without surrounding spaces.
func (text ConsentText) RenderForOrganization(organizationName string) (string, error) {
const location = "ConsentText.RenderForOrganization"
if !text.purpose.OrganizationScoped() {
return "", fmt.Errorf("%s - only the C4 text names an organization: %w", location, ErrInvalidConsentText)
}
if !validOrganizationName(organizationName) {
return "", fmt.Errorf("%s - organization name must be one line of 1 to %d characters: %w", location, maxOrganizationNameRunes, ErrInvalidConsentText)
}
return strings.ReplaceAll(text.body, ConsentTextOrganizationPlaceholder, organizationName), nil
}
func validOrganizationName(name string) bool {
if name == "" || !utf8.ValidString(name) || utf8.RuneCountInString(name) > maxOrganizationNameRunes {
return false
}
if strings.TrimSpace(name) != name {
return false
}
return !strings.ContainsFunc(name, unicode.IsControl)
}
// ConsentSource tells where a grant was given.
type ConsentSource string
const (
// ConsentSourceRegistration is the C1 acceptance in the registration.
ConsentSourceRegistration ConsentSource = "registration"
// ConsentSourceConsentSettings is a grant in the consent settings of the
// account, for C1-C3 and C5.
ConsentSourceConsentSettings ConsentSource = "consent_settings"
// ConsentSourceInvitationAcceptance is the C4 grant in the acceptance of
// an invitation.
ConsentSourceInvitationAcceptance ConsentSource = "invitation_acceptance"
)
// allowedFor reports whether a grant of purpose may come from the source.
func (source ConsentSource) allowedFor(purpose ConsentPurpose) bool {
switch source {
case ConsentSourceRegistration:
return purpose == ConsentPurposePersonalData
case ConsentSourceConsentSettings:
return !purpose.OrganizationScoped()
case ConsentSourceInvitationAcceptance:
return purpose.OrganizationScoped()
default:
return false
}
}
// ConsentRevocationSource tells who recorded a revocation.
type ConsentRevocationSource string
const (
// ConsentRevocationSourceConsentSettings is a revocation by the subject in
// the product.
ConsentRevocationSourceConsentSettings ConsentRevocationSource = "consent_settings"
// ConsentRevocationSourceSupportRequest is a revocation that an operator
// recorded on the subject's request through support.
ConsentRevocationSourceSupportRequest ConsentRevocationSource = "support_request"
)
func (source ConsentRevocationSource) known() bool {
return source == ConsentRevocationSourceConsentSettings || source == ConsentRevocationSourceSupportRequest
}
// ContactField is a kind of contact data that C4 can disclose to one
// organization; the values match the contract enum ContactFieldKind.
type ContactField string
const (
ContactFieldFullName ContactField = "full_name"
ContactFieldEmail ContactField = "email"
ContactFieldPhone ContactField = "phone"
ContactFieldTelegram ContactField = "telegram"
)
// ParseContactField accepts a known kind.
func ParseContactField(value string) (ContactField, error) {
field := ContactField(value)
switch field {
case ContactFieldFullName, ContactFieldEmail, ContactFieldPhone, ContactFieldTelegram:
return field, nil
default:
return "", fmt.Errorf("domain.ParseContactField - unknown contact field: %w", ErrInvalidConsent)
}
}
// ContactFieldSet is a non-empty set of distinct contact fields in canonical
// ascending byte order, the form the ledger stores. One kind never implies
// another.
type ContactFieldSet struct {
fields []ContactField
}
// NewContactFieldSet accepts one to four distinct known fields in any order.
// A repeated field is refused, as the contract's uniqueItems refuses it,
// rather than merged.
func NewContactFieldSet(fields ...ContactField) (ContactFieldSet, error) {
const location = "domain.NewContactFieldSet"
if len(fields) == 0 || len(fields) > maxContactFields {
return ContactFieldSet{}, fmt.Errorf("%s - set must have 1 to %d fields: %w", location, maxContactFields, ErrInvalidConsent)
}
canonical := make([]ContactField, 0, len(fields))
for _, field := range fields {
if _, err := ParseContactField(string(field)); err != nil {
return ContactFieldSet{}, fmt.Errorf("%s - validate field: %w", location, err)
}
if slices.Contains(canonical, field) {
return ContactFieldSet{}, fmt.Errorf("%s - fields must be distinct: %w", location, ErrInvalidConsent)
}
canonical = append(canonical, field)
}
slices.Sort(canonical)
return ContactFieldSet{fields: canonical}, nil
}
// Fields returns a copy of the fields in canonical order.
func (set ContactFieldSet) Fields() []ContactField { return slices.Clone(set.fields) }
// Contains reports whether the set covers field.
func (set ContactFieldSet) Contains(field ContactField) bool {
return slices.Contains(set.fields, field)
}
// Equal reports whether both sets cover the same fields.
func (set ContactFieldSet) Equal(other ContactFieldSet) bool {
return slices.Equal(set.fields, other.fields)
}
// IsZero reports a set not built by NewContactFieldSet.
func (set ContactFieldSet) IsZero() bool { return len(set.fields) == 0 }
// ConsentState is the state of a ledger record as the read model computes
// it from the ledger.
type ConsentState string
const (
// ConsentStateActive is an unrevoked record that is the newest of its
// purpose; every unrevoked C4 record is active, since each covers its
// own invitation.
ConsentStateActive ConsentState = "active"
// ConsentStateSuperseded is an unrevoked record of C1-C3 or C5 with a
// newer unrevoked record of the same purpose, typically for a newer
// text version. It stays valid evidence for its own time.
ConsentStateSuperseded ConsentState = "superseded"
// ConsentStateRevoked is a revoked record.
ConsentStateRevoked ConsentState = "revoked"
)
// ParseConsentState accepts a known state.
func ParseConsentState(value string) (ConsentState, error) {
state := ConsentState(value)
switch state {
case ConsentStateActive, ConsentStateSuperseded, ConsentStateRevoked:
return state, nil
default:
return "", fmt.Errorf("domain.ParseConsentState - unknown state: %w", ErrInvalidConsent)
}
}
// ConsentGrantInput describes a grant of C1, C2, C3, or C5. TextVersion and
// TextHash come from the ConsentText that the subject saw.
type ConsentGrantInput struct {
SubjectID uuid.UUID
Purpose ConsentPurpose
TextVersion ConsentTextVersion
TextHash ConsentTextHash
Source ConsentSource
GrantedAt time.Time
}
// ConsentGrant is a validated grant of C1, C2, C3, or C5, ready for the
// ledger. C4 is never a ConsentGrant: it needs its organization scope, see
// ContactConsentGrant.
type ConsentGrant struct {
id uuid.UUID
subjectID uuid.UUID
purpose ConsentPurpose
textVersion ConsentTextVersion
textHash ConsentTextHash
source ConsentSource
grantedAt time.Time
}
// NewConsentGrant validates input and assigns a UUIDv7 identifier.
func NewConsentGrant(input ConsentGrantInput) (ConsentGrant, error) {
const location = "domain.NewConsentGrant"
if _, err := ParseConsentPurpose(string(input.Purpose)); err != nil {
return ConsentGrant{}, fmt.Errorf("%s - validate purpose: %w", location, err)
}
if input.Purpose.OrganizationScoped() {
return ConsentGrant{}, fmt.Errorf("%s - C4 is granted only with its organization scope: %w", location, ErrInvalidConsent)
}
if err := validateGrantText(location, input.TextVersion, input.TextHash); err != nil {
return ConsentGrant{}, err
}
switch {
case input.SubjectID == uuid.Nil:
return ConsentGrant{}, fmt.Errorf("%s - subject ID must not be nil: %w", location, ErrInvalidConsent)
case !input.Source.allowedFor(input.Purpose):
return ConsentGrant{}, fmt.Errorf("%s - source does not allow the purpose: %w", location, ErrInvalidConsent)
case input.GrantedAt.IsZero():
return ConsentGrant{}, fmt.Errorf("%s - grant time must be set: %w", location, ErrInvalidConsent)
}
id, err := uuid.NewV7()
if err != nil {
return ConsentGrant{}, fmt.Errorf("%s - generate record ID: %w", location, err)
}
return ConsentGrant{
id: id,
subjectID: input.SubjectID,
purpose: input.Purpose,
textVersion: input.TextVersion,
textHash: input.TextHash,
source: input.Source,
grantedAt: input.GrantedAt,
}, nil
}
func (grant ConsentGrant) ID() uuid.UUID { return grant.id }
func (grant ConsentGrant) SubjectID() uuid.UUID { return grant.subjectID }
func (grant ConsentGrant) Purpose() ConsentPurpose { return grant.purpose }
func (grant ConsentGrant) TextVersion() ConsentTextVersion { return grant.textVersion }
func (grant ConsentGrant) TextHash() ConsentTextHash { return grant.textHash }
func (grant ConsentGrant) Source() ConsentSource { return grant.source }
func (grant ConsentGrant) GrantedAt() time.Time { return grant.grantedAt }
// IsZero reports a grant not built by NewConsentGrant.
func (grant ConsentGrant) IsZero() bool { return grant.id == uuid.Nil }
func (grant ConsentGrant) String() string {
return fmt.Sprintf("[consent grant %s %s]", grant.id, grant.purpose)
}
func (grant ConsentGrant) GoString() string { return grant.String() }
// Format applies String to every verb; without it %+v would print the
// subject.
func (grant ConsentGrant) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(grant.String()))
}
// LogValue carries only the record ID and purpose.
func (grant ConsentGrant) LogValue() slog.Value { return consentLogValue(grant.id, grant.purpose) }
// ContactConsentGrantInput describes the C4 grant of an invitation
// acceptance: the organization and its name as the candidate saw it, the
// selected fields, the invitation and the terms version it accepts, and the
// published C4 text. The grant computes the hash of the shown text itself;
// a caller never supplies hash bytes.
type ContactConsentGrantInput struct {
SubjectID uuid.UUID
OrganizationID uuid.UUID
OrganizationName string
Fields ContactFieldSet
InvitationID uuid.UUID
InvitationTermsVersion int64
Text ConsentText
GrantedAt time.Time
}
// ContactConsentGrant is a validated C4 grant with its scope. String,
// GoString, Format, and LogValue show only the record ID and purpose.
type ContactConsentGrant struct {
id uuid.UUID
subjectID uuid.UUID
organizationID uuid.UUID
organizationName string
fields ContactFieldSet
invitationID uuid.UUID
invitationTermsVersion int64
textVersion ConsentTextVersion
textHash ConsentTextHash
grantedAt time.Time
}
// NewContactConsentGrant validates input, renders the C4 text for the
// organization name, records the hash of that shown text, and assigns a
// UUIDv7 identifier. The database checks the same hash against the
// published text and the stored name.
func NewContactConsentGrant(input ContactConsentGrantInput) (ContactConsentGrant, error) {
const location = "domain.NewContactConsentGrant"
if input.Text.IsZero() || !input.Text.Purpose().OrganizationScoped() {
return ContactConsentGrant{}, fmt.Errorf("%s - C4 requires the published C4 text: %w", location, ErrInvalidConsentText)
}
shown, err := input.Text.RenderForOrganization(input.OrganizationName)
if err != nil {
return ContactConsentGrant{}, fmt.Errorf("%s - render the shown text: %w", location, err)
}
switch {
case input.SubjectID == uuid.Nil:
return ContactConsentGrant{}, fmt.Errorf("%s - subject ID must not be nil: %w", location, ErrInvalidConsent)
case input.OrganizationID == uuid.Nil:
return ContactConsentGrant{}, fmt.Errorf("%s - C4 requires an organization: %w", location, ErrInvalidConsent)
case input.Fields.IsZero():
return ContactConsentGrant{}, fmt.Errorf("%s - C4 requires a field set built by NewContactFieldSet: %w", location, ErrInvalidConsent)
case input.InvitationID == uuid.Nil:
return ContactConsentGrant{}, fmt.Errorf("%s - C4 requires an invitation: %w", location, ErrInvalidConsent)
case input.InvitationTermsVersion <= 0:
return ContactConsentGrant{}, fmt.Errorf("%s - invitation terms version must be positive: %w", location, ErrInvalidConsent)
case input.GrantedAt.IsZero():
return ContactConsentGrant{}, fmt.Errorf("%s - grant time must be set: %w", location, ErrInvalidConsent)
}
id, err := uuid.NewV7()
if err != nil {
return ContactConsentGrant{}, fmt.Errorf("%s - generate record ID: %w", location, err)
}
return ContactConsentGrant{
id: id,
subjectID: input.SubjectID,
organizationID: input.OrganizationID,
organizationName: input.OrganizationName,
fields: input.Fields,
invitationID: input.InvitationID,
invitationTermsVersion: input.InvitationTermsVersion,
textVersion: input.Text.Version(),
textHash: HashConsentText(shown),
grantedAt: input.GrantedAt,
}, nil
}
func (grant ContactConsentGrant) ID() uuid.UUID { return grant.id }
func (grant ContactConsentGrant) SubjectID() uuid.UUID { return grant.subjectID }
func (grant ContactConsentGrant) OrganizationID() uuid.UUID { return grant.organizationID }
func (grant ContactConsentGrant) OrganizationName() string { return grant.organizationName }
func (grant ContactConsentGrant) Fields() ContactFieldSet { return grant.fields }
func (grant ContactConsentGrant) InvitationID() uuid.UUID { return grant.invitationID }
func (grant ContactConsentGrant) InvitationTermsVersion() int64 { return grant.invitationTermsVersion }
func (grant ContactConsentGrant) TextVersion() ConsentTextVersion { return grant.textVersion }
func (grant ContactConsentGrant) TextHash() ConsentTextHash { return grant.textHash }
func (grant ContactConsentGrant) GrantedAt() time.Time { return grant.grantedAt }
// IsZero reports a grant not built by NewContactConsentGrant.
func (grant ContactConsentGrant) IsZero() bool { return grant.id == uuid.Nil }
func (grant ContactConsentGrant) String() string {
return fmt.Sprintf("[consent grant %s %s]", grant.id, ConsentPurposeContactDisclosure)
}
func (grant ContactConsentGrant) GoString() string { return grant.String() }
// Format applies String to every verb; without it %+v would print the
// subject, the organization, and the fields.
func (grant ContactConsentGrant) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(grant.String()))
}
// LogValue carries only the record ID and purpose.
func (grant ContactConsentGrant) LogValue() slog.Value {
return consentLogValue(grant.id, ConsentPurposeContactDisclosure)
}
func validateGrantText(location string, version ConsentTextVersion, hash ConsentTextHash) error {
if _, err := ParseConsentTextVersion(string(version)); err != nil {
return fmt.Errorf("%s - validate text version: %w", location, err)
}
if hash.IsZero() {
return fmt.Errorf("%s - text hash must be set: %w", location, ErrInvalidConsentText)
}
return nil
}
// ConsentRevocationInput describes a revocation of every unrevoked record of
// a purpose. OrganizationID is required for C4, which is revoked per
// organization, and must be uuid.Nil for every other purpose.
type ConsentRevocationInput struct {
SubjectID uuid.UUID
Purpose ConsentPurpose
OrganizationID uuid.UUID
Source ConsentRevocationSource
RevokedAt time.Time
}
// ConsentRevocation is a validated revocation.
type ConsentRevocation struct {
subjectID uuid.UUID
purpose ConsentPurpose
organizationID uuid.UUID
source ConsentRevocationSource
revokedAt time.Time
}
// NewConsentRevocation validates input.
func NewConsentRevocation(input ConsentRevocationInput) (ConsentRevocation, error) {
const location = "domain.NewConsentRevocation"
if _, err := ParseConsentPurpose(string(input.Purpose)); err != nil {
return ConsentRevocation{}, fmt.Errorf("%s - validate purpose: %w", location, err)
}
switch {
case input.SubjectID == uuid.Nil:
return ConsentRevocation{}, fmt.Errorf("%s - subject ID must not be nil: %w", location, ErrInvalidConsent)
case input.Purpose.OrganizationScoped() != (input.OrganizationID != uuid.Nil):
return ConsentRevocation{}, fmt.Errorf("%s - only C4 is revoked per organization, and always so: %w", location, ErrInvalidConsent)
case !input.Source.known():
return ConsentRevocation{}, fmt.Errorf("%s - unknown revocation source: %w", location, ErrInvalidConsent)
case input.RevokedAt.IsZero():
return ConsentRevocation{}, fmt.Errorf("%s - revocation time must be set: %w", location, ErrInvalidConsent)
}
return ConsentRevocation{
subjectID: input.SubjectID,
purpose: input.Purpose,
organizationID: input.OrganizationID,
source: input.Source,
revokedAt: input.RevokedAt,
}, nil
}
func (revocation ConsentRevocation) SubjectID() uuid.UUID { return revocation.subjectID }
func (revocation ConsentRevocation) Purpose() ConsentPurpose { return revocation.purpose }
func (revocation ConsentRevocation) OrganizationID() uuid.UUID { return revocation.organizationID }
func (revocation ConsentRevocation) Source() ConsentRevocationSource { return revocation.source }
func (revocation ConsentRevocation) RevokedAt() time.Time { return revocation.revokedAt }
func (revocation ConsentRevocation) IsZero() bool { return revocation.subjectID == uuid.Nil }
func (revocation ConsentRevocation) String() string {
return fmt.Sprintf("[consent revocation %s]", revocation.purpose)
}
func (revocation ConsentRevocation) GoString() string { return revocation.String() }
// Format applies String to every verb; without it %+v would print the
// subject and the organization.
func (revocation ConsentRevocation) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(revocation.String()))
}
// LogValue carries only the purpose and the source.
func (revocation ConsentRevocation) LogValue() slog.Value {
return slog.GroupValue(
slog.String("purpose", string(revocation.purpose)),
slog.String("revocation_source", string(revocation.source)),
)
}
// ConsentRecord is one row of the consent ledger as read back, with the
// state the read model computed. It is personal data of the subject:
// String, GoString, Format, and LogValue show only the record ID, purpose,
// and state, never the subject, the organization, or the fields.
type ConsentRecord struct {
id uuid.UUID
subjectID uuid.UUID
purpose ConsentPurpose
textVersion ConsentTextVersion
textHash ConsentTextHash
source ConsentSource
state ConsentState
grantedAt time.Time
revokedAt time.Time
revocationSource ConsentRevocationSource
organizationID uuid.UUID
organizationName string
fields ContactFieldSet
invitationID uuid.UUID
invitationTermsVersion int64
}
// StoredConsentRecord carries the columns of a stored record. Absent C4
// scope values are uuid.Nil, nil, and 0; an unrevoked record has a nil
// RevokedAt and an empty RevocationSource.
type StoredConsentRecord struct {
ID uuid.UUID
SubjectID uuid.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
State string
GrantedAt time.Time
RevokedAt *time.Time
RevocationSource string
OrganizationID uuid.UUID
OrganizationName string
FieldSet []string
InvitationID uuid.UUID
InvitationTermsVersion int64
}
// RestoreConsentRecord validates a stored record against the rules the
// database enforces, so a row changed outside the application fails with
// ErrInvalidConsent or ErrInvalidConsentText.
func RestoreConsentRecord(stored StoredConsentRecord) (ConsentRecord, error) {
const location = "domain.RestoreConsentRecord"
purpose, err := ParseConsentPurpose(stored.Purpose)
if err != nil {
return ConsentRecord{}, fmt.Errorf("%s - validate purpose: %w", location, err)
}
version, err := ParseConsentTextVersion(stored.TextVersion)
if err != nil {
return ConsentRecord{}, fmt.Errorf("%s - validate text version: %w", location, err)
}
hash, err := ConsentTextHashFromBytes(stored.TextHash)
if err != nil {
return ConsentRecord{}, fmt.Errorf("%s - validate text hash: %w", location, err)
}
state, err := ParseConsentState(stored.State)
if err != nil {
return ConsentRecord{}, fmt.Errorf("%s - validate state: %w", location, err)
}
record := ConsentRecord{
id: stored.ID,
subjectID: stored.SubjectID,
purpose: purpose,
textVersion: version,
textHash: hash,
source: ConsentSource(stored.Source),
state: state,
grantedAt: stored.GrantedAt,
revocationSource: ConsentRevocationSource(stored.RevocationSource),
organizationID: stored.OrganizationID,
organizationName: stored.OrganizationName,
invitationID: stored.InvitationID,
invitationTermsVersion: stored.InvitationTermsVersion,
}
if stored.RevokedAt != nil {
record.revokedAt = *stored.RevokedAt
}
if purpose.OrganizationScoped() {
fields, err := restoreContactFields(stored.FieldSet)
if err != nil {
return ConsentRecord{}, fmt.Errorf("%s - validate field set: %w", location, err)
}
record.fields = fields
}
if err := record.validate(stored.FieldSet != nil); err != nil {
return ConsentRecord{}, fmt.Errorf("%s - %w", location, err)
}
return record, nil
}
func restoreContactFields(stored []string) (ContactFieldSet, error) {
fields := make([]ContactField, 0, len(stored))
for _, value := range stored {
field, err := ParseContactField(value)
if err != nil {
return ContactFieldSet{}, err
}
fields = append(fields, field)
}
return NewContactFieldSet(fields...)
}
// validate checks the invariants that RestoreConsentRecord cannot express
// while parsing single values.
func (record ConsentRecord) validate(hasFieldSet bool) error {
switch {
case record.id == uuid.Nil || record.subjectID == uuid.Nil:
return fmt.Errorf("record and subject IDs must not be nil: %w", ErrInvalidConsent)
case !record.source.allowedFor(record.purpose):
return fmt.Errorf("source does not allow the purpose: %w", ErrInvalidConsent)
case record.grantedAt.IsZero():
return fmt.Errorf("grant time must be set: %w", ErrInvalidConsent)
}
if err := record.validateRevocation(); err != nil {
return err
}
return record.validateScope(hasFieldSet)
}
// validateRevocation mirrors consent_records_revocation_stamp and ties the
// computed state to the stamp.
func (record ConsentRecord) validateRevocation() error {
revoked := !record.revokedAt.IsZero()
switch {
case revoked != (record.revocationSource != ""):
return fmt.Errorf("revocation time and source must be set together: %w", ErrInvalidConsent)
case revoked && (!record.revocationSource.known() || record.revokedAt.Before(record.grantedAt)):
return fmt.Errorf("revocation must have a known source and follow the grant: %w", ErrInvalidConsent)
case revoked != (record.state == ConsentStateRevoked):
return fmt.Errorf("state must match the revocation: %w", ErrInvalidConsent)
}
return nil
}
// validateScope mirrors consent_records_c4_scope.
func (record ConsentRecord) validateScope(hasFieldSet bool) error {
if !record.purpose.OrganizationScoped() {
if record.organizationID != uuid.Nil || record.organizationName != "" || hasFieldSet ||
record.invitationID != uuid.Nil || record.invitationTermsVersion != 0 {
return fmt.Errorf("only a C4 record has an organization scope: %w", ErrInvalidConsent)
}
return nil
}
switch {
case record.state == ConsentStateSuperseded:
return fmt.Errorf("a C4 record is never superseded: %w", ErrInvalidConsent)
case record.organizationID == uuid.Nil || record.invitationID == uuid.Nil || record.invitationTermsVersion <= 0:
return fmt.Errorf("a C4 record must have its organization and invitation: %w", ErrInvalidConsent)
case !validOrganizationName(record.organizationName):
return fmt.Errorf("a C4 record must have the organization name it was shown with: %w", ErrInvalidConsent)
}
return nil
}
func (record ConsentRecord) ID() uuid.UUID { return record.id }
func (record ConsentRecord) SubjectID() uuid.UUID { return record.subjectID }
func (record ConsentRecord) Purpose() ConsentPurpose { return record.purpose }
func (record ConsentRecord) TextVersion() ConsentTextVersion { return record.textVersion }
func (record ConsentRecord) TextHash() ConsentTextHash { return record.textHash }
func (record ConsentRecord) Source() ConsentSource { return record.source }
func (record ConsentRecord) State() ConsentState { return record.state }
func (record ConsentRecord) GrantedAt() time.Time { return record.grantedAt }
// RevokedAt returns the revocation time and true for a revoked record.
func (record ConsentRecord) RevokedAt() (time.Time, bool) {
return record.revokedAt, !record.revokedAt.IsZero()
}
// RevocationSource is empty for an unrevoked record.
func (record ConsentRecord) RevocationSource() ConsentRevocationSource {
return record.revocationSource
}
// OrganizationID, OrganizationName, Fields, InvitationID, and
// InvitationTermsVersion hold the C4 scope and are zero for every other
// purpose. OrganizationName is the name the shown text carried at the time
// of the consent, not the current name of the organization.
func (record ConsentRecord) OrganizationID() uuid.UUID { return record.organizationID }
func (record ConsentRecord) OrganizationName() string { return record.organizationName }
func (record ConsentRecord) Fields() ContactFieldSet { return record.fields }
func (record ConsentRecord) InvitationID() uuid.UUID { return record.invitationID }
func (record ConsentRecord) InvitationTermsVersion() int64 { return record.invitationTermsVersion }
// IsZero reports a record not built by RestoreConsentRecord.
func (record ConsentRecord) IsZero() bool { return record.id == uuid.Nil }
func (record ConsentRecord) String() string {
return fmt.Sprintf("[consent %s %s %s]", record.id, record.purpose, record.state)
}
func (record ConsentRecord) GoString() string { return record.String() }
// Format applies String to every verb; without it %+v would print the
// subject and the scope.
func (record ConsentRecord) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(record.String()))
}
// LogValue carries only the record ID, purpose, and state.
func (record ConsentRecord) LogValue() slog.Value {
return slog.GroupValue(
slog.String("consent_record_id", record.id.String()),
slog.String("purpose", string(record.purpose)),
slog.String("state", string(record.state)),
)
}
func consentLogValue(id uuid.UUID, purpose ConsentPurpose) slog.Value {
return slog.GroupValue(
slog.String("consent_record_id", id.String()),
slog.String("purpose", string(purpose)),
)
}
+437
View File
@@ -0,0 +1,437 @@
package domain
import (
"bytes"
"errors"
"fmt"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
var consentTestTime = time.Date(2026, 10, 6, 9, 30, 0, 0, time.UTC)
const consentTestVersion ConsentTextVersion = "c1-2026-10-01"
func TestParseConsentPurposeAcceptsOnlyC1ToC5(t *testing.T) {
for _, value := range []string{"c1", "c2", "c3", "c4", "c5"} {
purpose, err := ParseConsentPurpose(value)
if err != nil {
t.Fatalf("ParseConsentPurpose(%q) error = %v", value, err)
}
if purpose.OrganizationScoped() != (value == "c4") {
t.Fatalf("%s.OrganizationScoped() = %v, want true only for c4", value, purpose.OrganizationScoped())
}
}
for _, value := range []string{"", "C1", "c0", "c6", "c1 "} {
if _, err := ParseConsentPurpose(value); !errors.Is(err, ErrInvalidConsent) {
t.Fatalf("ParseConsentPurpose(%q) error = %v, want ErrInvalidConsent", value, err)
}
}
}
func TestParseConsentTextVersionFollowsTheContractPattern(t *testing.T) {
for _, value := range []string{"c1-2026-10-01", "v1.2_rc", strings.Repeat("a", 64)} {
if _, err := ParseConsentTextVersion(value); err != nil {
t.Fatalf("ParseConsentTextVersion(%q) error = %v", value, err)
}
}
for _, value := range []string{"", " ", "c1 2026", "c1/2026", "версия", strings.Repeat("a", 65)} {
if _, err := ParseConsentTextVersion(value); !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("ParseConsentTextVersion(%q) error = %v, want ErrInvalidConsentText", value, err)
}
}
}
func TestConsentTextHashFromBytesRefusesEmptyAndMalformedDigests(t *testing.T) {
valid := HashConsentText("text")
if hash, err := ConsentTextHashFromBytes(valid[:]); err != nil || hash != valid {
t.Fatalf("ConsentTextHashFromBytes(valid) = %x, %v", hash, err)
}
for name, value := range map[string][]byte{
"nil": nil,
"empty": {},
"short": valid[:31],
"long": append(valid[:], 0),
"all zero": make([]byte, ConsentTextHashSize),
} {
if _, err := ConsentTextHashFromBytes(value); !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("ConsentTextHashFromBytes(%s) error = %v, want ErrInvalidConsentText", name, err)
}
}
}
func storedText(purpose, body string) StoredConsentText {
hash := HashConsentText(body)
return StoredConsentText{
Purpose: purpose,
Version: purpose + "-2026-10-01",
Body: body,
Hash: hash[:],
Kind: string(ConsentTextKindDemo),
PublishedAt: consentTestTime,
}
}
func TestRestoreConsentTextChecksTheHashAndThePlaceholder(t *testing.T) {
text, err := RestoreConsentText(storedText("c1", "I consent."))
if err != nil {
t.Fatalf("RestoreConsentText(c1) error = %v", err)
}
if text.Hash() != HashConsentText("I consent.") || text.Purpose() != ConsentPurposePersonalData {
t.Fatalf("restored text = %s %x, want the stored purpose and hash", text.Purpose(), text.Hash())
}
tampered := storedText("c1", "I consent.")
tampered.Body = "I consent to more."
changedKind := storedText("c1", "I consent.")
changedKind.Kind = "draft"
for name, stored := range map[string]StoredConsentText{
"body changed after hashing": tampered,
"C4 without the placeholder": storedText("c4", "I consent to the transfer."),
"C2 with the placeholder": storedText("c2", "I consent for {organization}."),
"unknown kind": changedKind,
"empty body": storedText("c3", ""),
} {
if _, err := RestoreConsentText(stored); !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("RestoreConsentText(%s) error = %v, want ErrInvalidConsentText", name, err)
}
}
}
func TestRenderForOrganizationNamesTheOrganizationOnlyInC4(t *testing.T) {
contact, err := RestoreConsentText(storedText("c4", "I consent to the transfer to {organization}."))
if err != nil {
t.Fatalf("RestoreConsentText(c4) error = %v", err)
}
shown, err := contact.RenderForOrganization("ООО Пример")
if err != nil {
t.Fatalf("RenderForOrganization() error = %v", err)
}
if shown != "I consent to the transfer to ООО Пример." {
t.Fatalf("RenderForOrganization() = %q", shown)
}
// The ledger stores the hash of the shown text, which differs per
// organization and from the hash of the published template.
other, err := contact.RenderForOrganization("Other LLC")
if err != nil {
t.Fatalf("RenderForOrganization(other) error = %v", err)
}
if HashConsentText(shown) == contact.Hash() || HashConsentText(shown) == HashConsentText(other) {
t.Fatal("the shown C4 text must hash differently per organization and from the template")
}
for _, name := range []string{"", " Leading", "Trailing ", "Two\nlines", strings.Repeat("я", 201)} {
if _, err := contact.RenderForOrganization(name); !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("RenderForOrganization(%q) error = %v, want ErrInvalidConsentText", name, err)
}
}
personalData, err := RestoreConsentText(storedText("c1", "I consent."))
if err != nil {
t.Fatalf("RestoreConsentText(c1) error = %v", err)
}
if _, err := personalData.RenderForOrganization("Acme"); !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("RenderForOrganization(C1) error = %v, want ErrInvalidConsentText", err)
}
}
func TestNewContactFieldSetIsCanonicalAndRefusesDuplicates(t *testing.T) {
set, err := NewContactFieldSet(ContactFieldTelegram, ContactFieldEmail, ContactFieldFullName)
if err != nil {
t.Fatalf("NewContactFieldSet() error = %v", err)
}
reordered, err := NewContactFieldSet(ContactFieldFullName, ContactFieldTelegram, ContactFieldEmail)
if err != nil {
t.Fatalf("NewContactFieldSet(reordered) error = %v", err)
}
if !set.Equal(reordered) || fmt.Sprint(set.Fields()) != "[email full_name telegram]" {
t.Fatalf("Fields() = %v, want the canonical order for any input order", set.Fields())
}
if set.Contains(ContactFieldPhone) {
t.Fatal("one field must never imply another")
}
fields := set.Fields()
fields[0] = ContactFieldPhone
if set.Contains(ContactFieldPhone) {
t.Fatal("Fields() must return a copy")
}
for name, input := range map[string][]ContactField{
"empty": nil,
"duplicate": {ContactFieldEmail, ContactFieldEmail},
"unknown": {ContactFieldEmail, "address"},
"too many": {ContactFieldEmail, ContactFieldPhone, ContactFieldTelegram, ContactFieldFullName, ContactFieldEmail},
} {
if _, err := NewContactFieldSet(input...); !errors.Is(err, ErrInvalidConsent) {
t.Fatalf("NewContactFieldSet(%s) error = %v, want ErrInvalidConsent", name, err)
}
}
}
func validGrantInput() ConsentGrantInput {
return ConsentGrantInput{
SubjectID: uuid.Must(uuid.NewV7()),
Purpose: ConsentPurposePersonalData,
TextVersion: consentTestVersion,
TextHash: HashConsentText("I consent."),
Source: ConsentSourceRegistration,
GrantedAt: consentTestTime,
}
}
func TestNewConsentGrantValidatesEveryField(t *testing.T) {
grant, err := NewConsentGrant(validGrantInput())
if err != nil {
t.Fatalf("NewConsentGrant() error = %v", err)
}
if grant.ID().Version() != 7 || grant.Purpose() != ConsentPurposePersonalData || grant.IsZero() {
t.Fatalf("grant = %s %s, want a UUIDv7 C1 grant", grant.ID(), grant.Purpose())
}
for name, change := range map[string]func(*ConsentGrantInput){
"C4 without its scope": func(input *ConsentGrantInput) {
input.Purpose, input.Source = ConsentPurposeContactDisclosure, ConsentSourceInvitationAcceptance
},
"unknown purpose": func(input *ConsentGrantInput) { input.Purpose = "c9" },
"empty text version": func(input *ConsentGrantInput) { input.TextVersion = "" },
"malformed text version": func(input *ConsentGrantInput) { input.TextVersion = "c1 v2" },
"missing text hash": func(input *ConsentGrantInput) { input.TextHash = ConsentTextHash{} },
"missing subject": func(input *ConsentGrantInput) { input.SubjectID = uuid.Nil },
"registration of C2": func(input *ConsentGrantInput) { input.Purpose = ConsentPurposePublication },
"invitation acceptance of C3": func(input *ConsentGrantInput) {
input.Purpose, input.Source = ConsentPurposeAutoCategorization, ConsentSourceInvitationAcceptance
},
"unknown source": func(input *ConsentGrantInput) { input.Source = "import" },
"missing grant time": func(input *ConsentGrantInput) { input.GrantedAt = time.Time{} },
} {
input := validGrantInput()
change(&input)
_, err := NewConsentGrant(input)
if !errors.Is(err, ErrInvalidConsent) && !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("NewConsentGrant(%s) error = %v, want a validation error", name, err)
}
}
}
const consentTestC4Body = "I consent to the transfer to {organization}."
func contactText(t *testing.T) ConsentText {
t.Helper()
text, err := RestoreConsentText(storedText("c4", consentTestC4Body))
if err != nil {
t.Fatalf("RestoreConsentText(c4) error = %v", err)
}
return text
}
func validContactGrantInput(t *testing.T) ContactConsentGrantInput {
t.Helper()
fields, err := NewContactFieldSet(ContactFieldEmail)
if err != nil {
t.Fatalf("NewContactFieldSet() error = %v", err)
}
return ContactConsentGrantInput{
SubjectID: uuid.Must(uuid.NewV7()),
OrganizationID: uuid.Must(uuid.NewV7()),
OrganizationName: "Acme",
Fields: fields,
InvitationID: uuid.Must(uuid.NewV7()),
InvitationTermsVersion: 2,
Text: contactText(t),
GrantedAt: consentTestTime,
}
}
func TestNewContactConsentGrantRequiresItsScope(t *testing.T) {
grant, err := NewContactConsentGrant(validContactGrantInput(t))
if err != nil {
t.Fatalf("NewContactConsentGrant() error = %v", err)
}
if grant.IsZero() || !grant.Fields().Contains(ContactFieldEmail) || grant.InvitationTermsVersion() != 2 ||
grant.OrganizationName() != "Acme" || grant.TextVersion() != "c4-2026-10-01" {
t.Fatalf("grant = %s, want the given scope", grant.ID())
}
// The grant hashes the text as shown for the organization; a caller
// never supplies hash bytes.
if grant.TextHash() != HashConsentText("I consent to the transfer to Acme.") {
t.Fatalf("TextHash() = %x, want the hash of the shown text", grant.TextHash())
}
personalData, err := RestoreConsentText(storedText("c1", "I consent."))
if err != nil {
t.Fatalf("RestoreConsentText(c1) error = %v", err)
}
for name, change := range map[string]func(*ContactConsentGrantInput){
"missing organization": func(input *ContactConsentGrantInput) { input.OrganizationID = uuid.Nil },
"missing organization name": func(input *ContactConsentGrantInput) { input.OrganizationName = "" },
"multi-line name": func(input *ContactConsentGrantInput) { input.OrganizationName = "Acme\nLLC" },
"missing field set": func(input *ContactConsentGrantInput) { input.Fields = ContactFieldSet{} },
"missing invitation": func(input *ContactConsentGrantInput) { input.InvitationID = uuid.Nil },
"non-positive terms version": func(input *ContactConsentGrantInput) { input.InvitationTermsVersion = 0 },
"missing subject": func(input *ContactConsentGrantInput) { input.SubjectID = uuid.Nil },
"missing text": func(input *ContactConsentGrantInput) { input.Text = ConsentText{} },
"text of another purpose": func(input *ContactConsentGrantInput) { input.Text = personalData },
"missing grant time": func(input *ContactConsentGrantInput) { input.GrantedAt = time.Time{} },
} {
input := validContactGrantInput(t)
change(&input)
_, err := NewContactConsentGrant(input)
if !errors.Is(err, ErrInvalidConsent) && !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("NewContactConsentGrant(%s) error = %v, want a validation error", name, err)
}
}
}
func TestGrantsAndRevocationsShowNoSubjectOrScope(t *testing.T) {
input := validContactGrantInput(t)
contact, err := NewContactConsentGrant(input)
if err != nil {
t.Fatalf("NewContactConsentGrant() error = %v", err)
}
personalInput := validGrantInput()
personal, err := NewConsentGrant(personalInput)
if err != nil {
t.Fatalf("NewConsentGrant() error = %v", err)
}
revocation, err := NewConsentRevocation(ConsentRevocationInput{
SubjectID: input.SubjectID, Purpose: ConsentPurposeContactDisclosure, OrganizationID: input.OrganizationID,
Source: ConsentRevocationSourceConsentSettings, RevokedAt: consentTestTime,
})
if err != nil {
t.Fatalf("NewConsentRevocation() error = %v", err)
}
var logs bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&logs, nil))
logger.Info("consent", "contact", contact, "personal", personal, "revocation", revocation)
output := logs.String() + fmt.Sprintf("%v %+v %#v %+v %+v", contact, contact, personal, revocation, struct{ Grant ContactConsentGrant }{contact})
for _, private := range []string{
input.SubjectID.String(), input.OrganizationID.String(), input.InvitationID.String(),
personalInput.SubjectID.String(), "Acme", "email",
} {
if strings.Contains(output, private) {
t.Fatalf("output %q contains %q", output, private)
}
}
}
func TestNewConsentRevocationScopesOnlyC4ByOrganization(t *testing.T) {
subject, organization := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7())
valid := []ConsentRevocationInput{
{SubjectID: subject, Purpose: ConsentPurposePublication, Source: ConsentRevocationSourceConsentSettings, RevokedAt: consentTestTime},
{SubjectID: subject, Purpose: ConsentPurposeContactDisclosure, OrganizationID: organization, Source: ConsentRevocationSourceSupportRequest, RevokedAt: consentTestTime},
}
for _, input := range valid {
if _, err := NewConsentRevocation(input); err != nil {
t.Fatalf("NewConsentRevocation(%s) error = %v", input.Purpose, err)
}
}
for name, input := range map[string]ConsentRevocationInput{
"C4 without an organization": {SubjectID: subject, Purpose: ConsentPurposeContactDisclosure, Source: ConsentRevocationSourceConsentSettings, RevokedAt: consentTestTime},
"C1 with an organization": {SubjectID: subject, Purpose: ConsentPurposePersonalData, OrganizationID: organization, Source: ConsentRevocationSourceConsentSettings, RevokedAt: consentTestTime},
"unknown source": {SubjectID: subject, Purpose: ConsentPurposePersonalData, Source: "admin", RevokedAt: consentTestTime},
"missing subject": {Purpose: ConsentPurposePersonalData, Source: ConsentRevocationSourceConsentSettings, RevokedAt: consentTestTime},
"missing time": {SubjectID: subject, Purpose: ConsentPurposePersonalData, Source: ConsentRevocationSourceConsentSettings},
} {
if _, err := NewConsentRevocation(input); !errors.Is(err, ErrInvalidConsent) {
t.Fatalf("NewConsentRevocation(%s) error = %v, want ErrInvalidConsent", name, err)
}
}
}
func storedRecord(purpose string) StoredConsentRecord {
hash := HashConsentText("shown text")
record := StoredConsentRecord{
ID: uuid.Must(uuid.NewV7()),
SubjectID: uuid.Must(uuid.NewV7()),
Purpose: purpose,
TextVersion: purpose + "-2026-10-01",
TextHash: hash[:],
Source: string(ConsentSourceConsentSettings),
State: string(ConsentStateActive),
GrantedAt: consentTestTime,
}
if purpose == "c4" {
record.Source = string(ConsentSourceInvitationAcceptance)
record.OrganizationID = uuid.Must(uuid.NewV7())
record.OrganizationName = "Acme"
record.FieldSet = []string{"phone", "email"}
record.InvitationID = uuid.Must(uuid.NewV7())
record.InvitationTermsVersion = 1
}
return record
}
func TestRestoreConsentRecordMirrorsTheLedgerConstraints(t *testing.T) {
for _, purpose := range []string{"c1", "c2", "c3", "c4", "c5"} {
if _, err := RestoreConsentRecord(storedRecord(purpose)); err != nil {
t.Fatalf("RestoreConsentRecord(%s) error = %v", purpose, err)
}
}
revokedAt := consentTestTime.Add(time.Hour)
earlier := consentTestTime.Add(-time.Hour)
for name, change := range map[string]func(*StoredConsentRecord){
"C4 without an organization": func(record *StoredConsentRecord) { record.OrganizationID = uuid.Nil },
"C4 without its name snapshot": func(record *StoredConsentRecord) { record.OrganizationName = "" },
"C4 with an empty field set": func(record *StoredConsentRecord) { record.FieldSet = []string{} },
"C4 superseded": func(record *StoredConsentRecord) {
record.State = string(ConsentStateSuperseded)
},
"C4 from the settings": func(record *StoredConsentRecord) { record.Source = string(ConsentSourceConsentSettings) },
"revoked state without a stamp": func(record *StoredConsentRecord) {
record.State = string(ConsentStateRevoked)
},
"stamp without a source": func(record *StoredConsentRecord) {
record.RevokedAt, record.State = &revokedAt, string(ConsentStateRevoked)
},
"revocation before the grant": func(record *StoredConsentRecord) {
record.RevokedAt, record.RevocationSource, record.State = &earlier, string(ConsentRevocationSourceConsentSettings), string(ConsentStateRevoked)
},
"empty hash": func(record *StoredConsentRecord) { record.TextHash = nil },
"empty version": func(record *StoredConsentRecord) { record.TextVersion = "" },
"unknown state": func(record *StoredConsentRecord) { record.State = "pending" },
} {
record := storedRecord("c4")
change(&record)
_, err := RestoreConsentRecord(record)
if !errors.Is(err, ErrInvalidConsent) && !errors.Is(err, ErrInvalidConsentText) {
t.Fatalf("RestoreConsentRecord(%s) error = %v, want a validation error", name, err)
}
}
scoped := storedRecord("c3")
scoped.FieldSet = []string{"email"}
if _, err := RestoreConsentRecord(scoped); !errors.Is(err, ErrInvalidConsent) {
t.Fatalf("RestoreConsentRecord(C3 with fields) error = %v, want ErrInvalidConsent", err)
}
named := storedRecord("c1")
named.OrganizationName = "Acme"
if _, err := RestoreConsentRecord(named); !errors.Is(err, ErrInvalidConsent) {
t.Fatalf("RestoreConsentRecord(C1 with an organization name) error = %v, want ErrInvalidConsent", err)
}
}
func TestConsentRecordOutputShowsNoSubjectOrScope(t *testing.T) {
stored := storedRecord("c4")
record, err := RestoreConsentRecord(stored)
if err != nil {
t.Fatalf("RestoreConsentRecord() error = %v", err)
}
var logs bytes.Buffer
for _, logger := range []*slog.Logger{
slog.New(slog.NewTextHandler(&logs, nil)),
slog.New(slog.NewJSONHandler(&logs, nil)),
} {
logger.Info("consent", "record", record)
}
output := strings.Join([]string{
logs.String(),
fmt.Sprintf("%v %+v %#v %s", record, record, record, record),
fmt.Sprintf("%+v", struct{ Record ConsentRecord }{record}),
}, "\n")
for _, private := range []string{stored.SubjectID.String(), stored.OrganizationID.String(), stored.InvitationID.String(), "phone", "Acme"} {
if strings.Contains(output, private) {
t.Fatalf("output %q contains %q", output, private)
}
}
if !strings.Contains(output, record.ID().String()) || !strings.Contains(output, "c4") {
t.Fatalf("output %q, want the record ID and purpose", output)
}
}