866 lines
35 KiB
Go
866 lines
35 KiB
Go
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)),
|
|
)
|
|
}
|