Files
lincodex/backend/internal/adapter/secondary/postgres/consents.go
T

410 lines
17 KiB
Go

package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// consentConstraintErrors maps the consent constraints whose violation is a
// caller-visible outcome to port sentinels by SQLSTATE and constraint name,
// never by text. The duplicate grants of the ledger are no errors: the
// inserts use ON CONFLICT DO NOTHING.
var consentConstraintErrors = map[constraintViolation]error{
{foreignKeyViolationCode, "account_deletion_requests_subject_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "consent_records_subject_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "consent_records_text_fkey"}: outbound.ErrConsentTextNotFound,
{foreignKeyViolationCode, "consent_records_published_text_fkey"}: outbound.ErrConsentTextMismatch,
{checkViolationCode, "consent_records_text_published"}: outbound.ErrConsentTextNotPublished,
{checkViolationCode, "consent_records_c4_text_hash"}: outbound.ErrConsentTextMismatch,
// The revoke queries clamp the time to the grant, so this stays a
// backstop for a revocation written around them.
{checkViolationCode, "consent_records_revocation_stamp"}: domain.ErrInvalidConsent,
{integrityConstraintViolationCode, "consent_records_retained"}: outbound.ErrConsentRecordImmutable,
{integrityConstraintViolationCode, "consent_records_immutable"}: outbound.ErrConsentRecordImmutable,
}
// mapConsentError turns a known consent constraint or trigger error into its
// port sentinel and keeps the constraint name. Any other PostgreSQL error is
// replaced by its SQLSTATE and constraint name, because its detail can quote
// the subject, the organization, or the field set. Deadlocks and
// serialization failures also match ErrTransactionConflict. A connection
// error loses the pgx prefix that names the database user and database.
func mapConsentError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
if sentinel, ok := consentConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok {
return fmt.Errorf("postgres.mapConsentError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
// ConsentStore provides the consent repositories outside a transaction.
// Every call runs as its own statement on a pool connection. Called with a
// context that belongs to a Transactor callback, it fails with
// outbound.ErrNestedTransaction; use the UnitOfWork accessors there.
type ConsentStore struct {
queries *sqlc.Queries
}
func NewConsentStore(pool *pgxpool.Pool) *ConsentStore {
return &ConsentStore{queries: sqlc.New(standaloneDB{pool: pool})}
}
var (
_ outbound.ConsentRepositories = (*ConsentStore)(nil)
_ outbound.ConsentRepositories = (*UnitOfWork)(nil)
)
func (store *ConsentStore) ConsentTexts() outbound.ConsentTextRepository {
return consentTextRepository{queries: store.queries}
}
func (store *ConsentStore) ConsentLedger() outbound.ConsentLedger {
return consentLedger{queries: store.queries}
}
func (unit *UnitOfWork) ConsentTexts() outbound.ConsentTextRepository {
return consentTextRepository{queries: unit.queries}
}
func (unit *UnitOfWork) ConsentLedger() outbound.ConsentLedger {
return consentLedger{queries: unit.queries}
}
type consentTextRepository struct {
queries *sqlc.Queries
}
func (repository consentTextRepository) Get(
ctx context.Context,
purpose domain.ConsentPurpose,
version domain.ConsentTextVersion,
) (domain.ConsentText, error) {
row, err := repository.queries.GetConsentText(ctx, sqlc.GetConsentTextParams{Purpose: string(purpose), Version: string(version)})
if err != nil {
return domain.ConsentText{}, fmt.Errorf("consentTextRepository.Get - select consent text: %w", mapConsentNoRows(err, outbound.ErrConsentTextNotFound))
}
return consentTextFromRow(row)
}
func (repository consentTextRepository) Current(ctx context.Context, purpose domain.ConsentPurpose, at time.Time) (domain.ConsentText, error) {
if err := requireTime("consentTextRepository.Current", at, domain.ErrInvalidConsentText); err != nil {
return domain.ConsentText{}, err
}
row, err := repository.queries.GetCurrentConsentText(ctx, sqlc.GetCurrentConsentTextParams{Purpose: string(purpose), At: pgTime(at)})
if err != nil {
return domain.ConsentText{}, fmt.Errorf("consentTextRepository.Current - select consent text: %w", mapConsentNoRows(err, outbound.ErrConsentTextNotFound))
}
return consentTextFromRow(row)
}
func consentTextFromRow(row sqlc.ConsentText) (domain.ConsentText, error) {
text, err := domain.RestoreConsentText(domain.StoredConsentText{
Purpose: row.Purpose,
Version: row.Version,
Body: row.Body,
Hash: row.BodySha256,
Kind: row.Kind,
PublishedAt: row.PublishedAt.Time,
})
if err != nil {
return domain.ConsentText{}, fmt.Errorf("postgres.consentTextFromRow - restore consent text: %w", err)
}
return text, nil
}
type consentLedger struct {
queries *sqlc.Queries
}
var _ outbound.ConsentLedger = consentLedger{}
func (ledger consentLedger) Grant(ctx context.Context, grant domain.ConsentGrant) (domain.ConsentRecord, bool, error) {
if grant.IsZero() {
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.Grant - grant was not built by domain.NewConsentGrant: %w", domain.ErrInvalidConsent)
}
hash := grant.TextHash()
row, err := ledger.queries.InsertConsentRecord(ctx, sqlc.InsertConsentRecordParams{
ID: pgUUID(grant.ID()),
SubjectID: pgUUID(grant.SubjectID()),
Purpose: string(grant.Purpose()),
TextVersion: string(grant.TextVersion()),
TextHash: hash[:],
Source: string(grant.Source()),
RegistrationVersion: pgtype.Int8{
Int64: grant.RegistrationVersion(),
Valid: grant.RegistrationVersion() > 0,
},
GrantedAt: pgTime(grant.GrantedAt()),
})
if err == nil {
record, err := consentRecordFromRow(consentRecordRow(row))
return record, err == nil, err
}
if !errors.Is(err, pgx.ErrNoRows) {
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.Grant - insert consent record: %w", mapConsentError(err))
}
existing, err := ledger.queries.GetUnrevokedConsentRecordByVersion(ctx, sqlc.GetUnrevokedConsentRecordByVersionParams{
SubjectID: pgUUID(grant.SubjectID()),
Purpose: string(grant.Purpose()),
TextVersion: string(grant.TextVersion()),
})
if errors.Is(err, pgx.ErrNoRows) {
// The conflicting record was revoked between the two statements. A
// retry of the operation inserts a new record.
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.Grant - conflicting record was revoked concurrently: %w", outbound.ErrTransactionConflict)
}
if err != nil {
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.Grant - select existing consent record: %w", mapConsentError(err))
}
record, err := consentRecordFromRow(consentRecordRow(existing))
return record, false, err
}
func (ledger consentLedger) GrantContact(ctx context.Context, grant domain.ContactConsentGrant) (domain.ConsentRecord, bool, error) {
if grant.IsZero() {
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.GrantContact - grant was not built by domain.NewContactConsentGrant: %w", domain.ErrInvalidConsent)
}
hash := grant.TextHash()
row, err := ledger.queries.InsertContactConsentRecord(ctx, sqlc.InsertContactConsentRecordParams{
ID: pgUUID(grant.ID()),
SubjectID: pgUUID(grant.SubjectID()),
TextVersion: string(grant.TextVersion()),
TextHash: hash[:],
OrganizationID: pgUUID(grant.OrganizationID()),
OrganizationName: pgtype.Text{String: grant.OrganizationName(), Valid: true},
FieldSet: contactFieldStrings(grant.Fields()),
InvitationID: pgUUID(grant.InvitationID()),
InvitationTermsVersion: pgtype.Int8{Int64: grant.InvitationTermsVersion(), Valid: true},
GrantedAt: pgTime(grant.GrantedAt()),
})
if err == nil {
record, err := consentRecordFromRow(consentRecordRow(row))
return record, err == nil, err
}
if !errors.Is(err, pgx.ErrNoRows) {
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.GrantContact - insert consent record: %w", mapConsentError(err))
}
existing, err := ledger.queries.GetContactConsentRecordByInvitation(ctx, sqlc.GetContactConsentRecordByInvitationParams{
SubjectID: pgUUID(grant.SubjectID()),
InvitationID: pgUUID(grant.InvitationID()),
})
if errors.Is(err, pgx.ErrNoRows) {
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.GrantContact - select existing consent record: %w", outbound.ErrConsentInvitationTaken)
}
if err != nil {
return domain.ConsentRecord{}, false, fmt.Errorf("consentLedger.GrantContact - select existing consent record: %w", mapConsentError(err))
}
record, err := consentRecordFromRow(consentRecordRow(existing))
return record, false, err
}
func (ledger consentLedger) Revoke(ctx context.Context, revocation domain.ConsentRevocation) ([]domain.ConsentRecord, error) {
if revocation.IsZero() {
return nil, fmt.Errorf("consentLedger.Revoke - revocation was not built by domain.NewConsentRevocation: %w", domain.ErrInvalidConsent)
}
source := pgtype.Text{String: string(revocation.Source()), Valid: true}
if revocation.Purpose().OrganizationScoped() {
rows, err := ledger.queries.RevokeContactConsentRecords(ctx, sqlc.RevokeContactConsentRecordsParams{
RevokedAt: pgTime(revocation.RevokedAt()),
RevocationSource: source,
SubjectID: pgUUID(revocation.SubjectID()),
OrganizationID: pgUUID(revocation.OrganizationID()),
})
if err != nil {
return nil, fmt.Errorf("consentLedger.Revoke - revoke contact consent records: %w", mapConsentError(err))
}
return consentRecordsFromRows(rows, func(row sqlc.RevokeContactConsentRecordsRow) consentRecordRow { return consentRecordRow(row) })
}
rows, err := ledger.queries.RevokeConsentRecords(ctx, sqlc.RevokeConsentRecordsParams{
RevokedAt: pgTime(revocation.RevokedAt()),
RevocationSource: source,
SubjectID: pgUUID(revocation.SubjectID()),
Purpose: string(revocation.Purpose()),
})
if err != nil {
return nil, fmt.Errorf("consentLedger.Revoke - revoke consent records: %w", mapConsentError(err))
}
return consentRecordsFromRows(rows, func(row sqlc.RevokeConsentRecordsRow) consentRecordRow { return consentRecordRow(row) })
}
func (ledger consentLedger) Current(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error) {
if _, err := domain.ParseConsentPurpose(string(purpose)); err != nil {
return domain.ConsentRecord{}, fmt.Errorf("consentLedger.Current - validate purpose: %w", err)
}
if purpose.OrganizationScoped() {
return domain.ConsentRecord{}, fmt.Errorf("consentLedger.Current - C4 is read per organization with CurrentContact: %w", domain.ErrInvalidConsent)
}
row, err := ledger.queries.GetCurrentConsentRecord(ctx, sqlc.GetCurrentConsentRecordParams{SubjectID: pgUUID(subjectID), Purpose: string(purpose)})
if err != nil {
return domain.ConsentRecord{}, fmt.Errorf("consentLedger.Current - select consent record: %w", mapConsentNoRows(err, outbound.ErrConsentNotFound))
}
return consentRecordFromRow(consentRecordRow(row))
}
func (ledger consentLedger) LockRegistration(
ctx context.Context,
subjectID uuid.UUID,
registrationVersion int64,
) (domain.ConsentRecord, error) {
const location = "consentLedger.LockRegistration"
if subjectID == uuid.Nil || registrationVersion <= 0 {
return domain.ConsentRecord{}, fmt.Errorf("%s - subject and registration version must be set: %w", location, domain.ErrInvalidConsent)
}
row, err := ledger.queries.LockRegistrationConsentRecord(ctx, sqlc.LockRegistrationConsentRecordParams{
SubjectID: pgUUID(subjectID),
RegistrationVersion: pgtype.Int8{Int64: registrationVersion, Valid: true},
})
if err != nil {
return domain.ConsentRecord{}, fmt.Errorf("%s - lock registration C1: %w", location, mapConsentNoRows(err, outbound.ErrConsentNotFound))
}
return consentRecordFromRow(consentRecordRow(row))
}
func (ledger consentLedger) CurrentContact(ctx context.Context, subjectID, organizationID uuid.UUID) ([]domain.ConsentRecord, error) {
rows, err := ledger.queries.ListCurrentContactConsentRecords(ctx, sqlc.ListCurrentContactConsentRecordsParams{
SubjectID: pgUUID(subjectID),
OrganizationID: pgUUID(organizationID),
})
if err != nil {
return nil, fmt.Errorf("consentLedger.CurrentContact - select consent records: %w", mapConsentError(err))
}
return consentRecordsFromRows(rows, func(row sqlc.ListCurrentContactConsentRecordsRow) consentRecordRow { return consentRecordRow(row) })
}
func (ledger consentLedger) List(ctx context.Context, query outbound.ConsentListQuery) (outbound.ConsentPage, error) {
const location = "consentLedger.List"
if query.SubjectID == uuid.Nil {
return outbound.ConsentPage{}, fmt.Errorf("%s - subject ID must not be nil: %w", location, domain.ErrInvalidConsent)
}
if query.Limit < 1 || query.Limit > outbound.MaxConsentPageSize {
return outbound.ConsentPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxConsentPageSize, domain.ErrInvalidConsent)
}
params := sqlc.ListConsentRecordsParams{
SubjectID: pgUUID(query.SubjectID),
// One extra row tells whether another page follows.
RowLimit: query.Limit + 1,
}
if query.State != "" {
if _, err := domain.ParseConsentState(string(query.State)); err != nil {
return outbound.ConsentPage{}, fmt.Errorf("%s - validate state: %w", location, err)
}
params.State = pgtype.Text{String: string(query.State), Valid: true}
}
if query.After != nil {
if err := requireTime(location, query.After.GrantedAt, domain.ErrInvalidConsent); err != nil {
return outbound.ConsentPage{}, err
}
params.AfterGrantedAt = pgTime(query.After.GrantedAt)
params.AfterID = pgUUID(query.After.ID)
}
rows, err := ledger.queries.ListConsentRecords(ctx, params)
if err != nil {
return outbound.ConsentPage{}, fmt.Errorf("%s - select consent records: %w", location, mapConsentError(err))
}
page := outbound.ConsentPage{HasMore: len(rows) > int(query.Limit)}
if page.HasMore {
rows = rows[:query.Limit]
}
page.Records, err = consentRecordsFromRows(rows, func(row sqlc.ListConsentRecordsRow) consentRecordRow { return consentRecordRow(row) })
if err != nil {
return outbound.ConsentPage{}, err
}
return page, nil
}
// consentRecordRow has the columns that every record query returns. The
// generated row types of those queries convert to it.
type consentRecordRow struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
RegistrationVersion pgtype.Int8
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
InvitationID pgtype.UUID
InvitationTermsVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
State string
}
func consentRecordFromRow(row consentRecordRow) (domain.ConsentRecord, error) {
record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{
ID: optionalUUID(row.ID),
SubjectID: optionalUUID(row.SubjectID),
Purpose: row.Purpose,
TextVersion: row.TextVersion,
TextHash: row.TextHash,
Source: row.Source,
RegistrationVersion: optionalConsentRegistrationVersion(row.RegistrationVersion),
State: row.State,
GrantedAt: row.GrantedAt.Time,
RevokedAt: optionalTime(row.RevokedAt),
RevocationSource: row.RevocationSource.String,
OrganizationID: optionalUUID(row.OrganizationID),
OrganizationName: row.OrganizationName.String,
FieldSet: row.FieldSet,
InvitationID: optionalUUID(row.InvitationID),
InvitationTermsVersion: row.InvitationTermsVersion.Int64,
})
if err != nil {
return domain.ConsentRecord{}, fmt.Errorf("postgres.consentRecordFromRow - restore consent record: %w", err)
}
return record, nil
}
func optionalConsentRegistrationVersion(value pgtype.Int8) int64 {
if !value.Valid {
return 0
}
return value.Int64
}
func consentRecordsFromRows[Row any](rows []Row, convert func(Row) consentRecordRow) ([]domain.ConsentRecord, error) {
records := make([]domain.ConsentRecord, 0, len(rows))
for _, row := range rows {
record, err := consentRecordFromRow(convert(row))
if err != nil {
return nil, err
}
records = append(records, record)
}
return records, nil
}
func contactFieldStrings(set domain.ContactFieldSet) []string {
fields := set.Fields()
values := make([]string, 0, len(fields))
for _, field := range fields {
values = append(values, string(field))
}
return values
}
func mapConsentNoRows(err, sentinel error) error {
if errors.Is(err, pgx.ErrNoRows) {
return sentinel
}
return mapConsentError(err)
}