feat(consent): add versioned append-only consent ledger C1-C5
This commit is contained in:
1 parent
008254e44a
commit
de49f93b0b
64 files changed
+9244
-132
No files matched your search
@@ -0,0 +1,376 @@
|
||||
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, "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()),
|
||||
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) 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
|
||||
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,
|
||||
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 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)
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// consentDetailMarker stands for a row value that a PostgreSQL detail can
|
||||
// quote, such as the subject or the field set.
|
||||
const consentDetailMarker = "Key (subject_id)=(01928f7a-0000-7000-8000-00000000c0de)"
|
||||
|
||||
func TestMapConsentErrorRecognizesLedgerConstraints(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
code string
|
||||
constraint string
|
||||
want error
|
||||
}{
|
||||
{code: foreignKeyViolationCode, constraint: "consent_records_subject_id_fkey", want: outbound.ErrUserNotFound},
|
||||
{code: foreignKeyViolationCode, constraint: "consent_records_text_fkey", want: outbound.ErrConsentTextNotFound},
|
||||
{code: foreignKeyViolationCode, constraint: "consent_records_published_text_fkey", want: outbound.ErrConsentTextMismatch},
|
||||
{code: checkViolationCode, constraint: "consent_records_text_published", want: outbound.ErrConsentTextNotPublished},
|
||||
{code: checkViolationCode, constraint: "consent_records_c4_text_hash", want: outbound.ErrConsentTextMismatch},
|
||||
{code: checkViolationCode, constraint: "consent_records_revocation_stamp", want: domain.ErrInvalidConsent},
|
||||
{code: integrityConstraintViolationCode, constraint: "consent_records_retained", want: outbound.ErrConsentRecordImmutable},
|
||||
{code: integrityConstraintViolationCode, constraint: "consent_records_immutable", want: outbound.ErrConsentRecordImmutable},
|
||||
} {
|
||||
err := mapConsentError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: consentDetailMarker})
|
||||
if !errors.Is(err, test.want) {
|
||||
t.Fatalf("mapConsentError(%s %s) = %v, want %v", test.code, test.constraint, err, test.want)
|
||||
}
|
||||
if !strings.Contains(err.Error(), test.constraint) || strings.Contains(err.Error(), "subject_id)=") {
|
||||
t.Fatalf("mapConsentError(%s) = %v, want the constraint name and no detail", test.constraint, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapConsentErrorDropsDetailOfOtherErrors(t *testing.T) {
|
||||
// A CHECK violation that the domain should have prevented keeps only the
|
||||
// SQLSTATE and the constraint, never the failing row.
|
||||
original := &pgconn.PgError{Code: checkViolationCode, ConstraintName: "consent_records_c4_scope", Detail: "Failing row contains (" + consentDetailMarker + ", {email,phone})."}
|
||||
err := mapConsentError(original)
|
||||
var stateError sqlStateError
|
||||
if !errors.As(err, &stateError) || stateError.SQLState() != checkViolationCode {
|
||||
t.Fatalf("mapConsentError() = %v, want SQLSTATE %s", err, checkViolationCode)
|
||||
}
|
||||
if strings.Contains(err.Error(), "Failing row") || strings.Contains(err.Error(), "phone") {
|
||||
t.Fatalf("mapConsentError() = %v, want no row values", err)
|
||||
}
|
||||
if err := mapConsentError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(err, outbound.ErrTransactionConflict) {
|
||||
t.Fatalf("mapConsentError(deadlock) = %v, want ErrTransactionConflict", err)
|
||||
}
|
||||
if err := mapConsentError(context.Canceled); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("mapConsentError(context.Canceled) = %v, want the original error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsentLedgerRejectsInvalidInputBeforeQuerying(t *testing.T) {
|
||||
// A ledger without queries proves that no statement runs.
|
||||
ledger := consentLedger{}
|
||||
ctx := t.Context()
|
||||
subject := uuid.Must(uuid.NewV7())
|
||||
if _, _, err := ledger.Grant(ctx, domain.ConsentGrant{}); !errors.Is(err, domain.ErrInvalidConsent) {
|
||||
t.Fatalf("Grant(zero grant) error = %v, want ErrInvalidConsent", err)
|
||||
}
|
||||
if _, _, err := ledger.GrantContact(ctx, domain.ContactConsentGrant{}); !errors.Is(err, domain.ErrInvalidConsent) {
|
||||
t.Fatalf("GrantContact(zero grant) error = %v, want ErrInvalidConsent", err)
|
||||
}
|
||||
if _, err := ledger.Revoke(ctx, domain.ConsentRevocation{}); !errors.Is(err, domain.ErrInvalidConsent) {
|
||||
t.Fatalf("Revoke(zero revocation) error = %v, want ErrInvalidConsent", err)
|
||||
}
|
||||
if _, err := ledger.Current(ctx, subject, domain.ConsentPurposeContactDisclosure); !errors.Is(err, domain.ErrInvalidConsent) {
|
||||
t.Fatalf("Current(C4) error = %v, want ErrInvalidConsent", err)
|
||||
}
|
||||
if _, err := ledger.Current(ctx, subject, "c9"); !errors.Is(err, domain.ErrInvalidConsent) {
|
||||
t.Fatalf("Current(unknown purpose) error = %v, want ErrInvalidConsent", err)
|
||||
}
|
||||
for _, query := range []outbound.ConsentListQuery{
|
||||
{Limit: 10},
|
||||
{SubjectID: subject, Limit: 0},
|
||||
{SubjectID: subject, Limit: outbound.MaxConsentPageSize + 1},
|
||||
{SubjectID: subject, Limit: 10, State: "pending"},
|
||||
{SubjectID: subject, Limit: 10, After: &outbound.ConsentListPosition{ID: subject}},
|
||||
} {
|
||||
if _, err := ledger.List(ctx, query); !errors.Is(err, domain.ErrInvalidConsent) {
|
||||
t.Fatalf("List(%+v) error = %v, want ErrInvalidConsent", query, err)
|
||||
}
|
||||
}
|
||||
if _, err := (consentTextRepository{}).Current(ctx, domain.ConsentPurposePersonalData, time.Time{}); !errors.Is(err, domain.ErrInvalidConsentText) {
|
||||
t.Fatalf("ConsentTexts.Current(zero time) error = %v, want ErrInvalidConsentText", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Every record query returns the same columns, so each generated row type
|
||||
// converts to consentRecordRow. A query that changes its columns breaks this
|
||||
// test at compile time instead of mapping a column wrongly.
|
||||
var (
|
||||
_ = consentRecordRow(sqlc.InsertConsentRecordRow{})
|
||||
_ = consentRecordRow(sqlc.InsertContactConsentRecordRow{})
|
||||
_ = consentRecordRow(sqlc.GetUnrevokedConsentRecordByVersionRow{})
|
||||
_ = consentRecordRow(sqlc.GetContactConsentRecordByInvitationRow{})
|
||||
_ = consentRecordRow(sqlc.GetCurrentConsentRecordRow{})
|
||||
_ = consentRecordRow(sqlc.ListCurrentContactConsentRecordsRow{})
|
||||
_ = consentRecordRow(sqlc.RevokeConsentRecordsRow{})
|
||||
_ = consentRecordRow(sqlc.RevokeContactConsentRecordsRow{})
|
||||
_ = consentRecordRow(sqlc.ListConsentRecordsRow{})
|
||||
)
|
||||
|
||||
func TestConsentRecordFromRowMapsNullableScope(t *testing.T) {
|
||||
grantedAt := time.Date(2026, 10, 6, 9, 30, 0, 0, time.UTC)
|
||||
hash := domain.HashConsentText("shown text")
|
||||
subject := uuid.Must(uuid.NewV7())
|
||||
organization := uuid.Must(uuid.NewV7())
|
||||
invitation := uuid.Must(uuid.NewV7())
|
||||
|
||||
contact, err := consentRecordFromRow(consentRecordRow{
|
||||
ID: pgUUID(uuid.Must(uuid.NewV7())),
|
||||
SubjectID: pgUUID(subject),
|
||||
Purpose: "c4",
|
||||
TextVersion: "c4-2026-10-01",
|
||||
TextHash: hash[:],
|
||||
Source: "invitation_acceptance",
|
||||
OrganizationID: pgUUID(organization),
|
||||
OrganizationName: pgtype.Text{String: "Acme", Valid: true},
|
||||
FieldSet: []string{"email", "phone"},
|
||||
InvitationID: pgUUID(invitation),
|
||||
InvitationTermsVersion: pgtype.Int8{Int64: 3, Valid: true},
|
||||
GrantedAt: pgTime(grantedAt),
|
||||
RevokedAt: pgTime(grantedAt.Add(time.Hour)),
|
||||
RevocationSource: pgtype.Text{String: "consent_settings", Valid: true},
|
||||
State: "revoked",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("consentRecordFromRow(C4) error = %v", err)
|
||||
}
|
||||
if contact.OrganizationID() != organization || contact.OrganizationName() != "Acme" || contact.InvitationID() != invitation || contact.InvitationTermsVersion() != 3 ||
|
||||
!contact.Fields().Contains(domain.ContactFieldPhone) || contact.Fields().Contains(domain.ContactFieldFullName) {
|
||||
t.Fatalf("C4 scope = %s, %s, %d, %v; want the stored scope", contact.OrganizationID(), contact.InvitationID(), contact.InvitationTermsVersion(), contact.Fields().Fields())
|
||||
}
|
||||
if revokedAt, revoked := contact.RevokedAt(); !revoked || !revokedAt.Equal(grantedAt.Add(time.Hour)) || contact.RevocationSource() != domain.ConsentRevocationSourceConsentSettings {
|
||||
t.Fatalf("revocation = %v %v %q, want the stored stamp", revokedAt, revoked, contact.RevocationSource())
|
||||
}
|
||||
|
||||
personalData, err := consentRecordFromRow(consentRecordRow{
|
||||
ID: pgUUID(uuid.Must(uuid.NewV7())),
|
||||
SubjectID: pgUUID(subject),
|
||||
Purpose: "c1",
|
||||
TextVersion: "c1-2026-10-01",
|
||||
TextHash: hash[:],
|
||||
Source: "registration",
|
||||
GrantedAt: pgTime(grantedAt),
|
||||
State: "active",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("consentRecordFromRow(C1) error = %v", err)
|
||||
}
|
||||
if personalData.OrganizationID() != uuid.Nil || !personalData.Fields().IsZero() || personalData.InvitationID() != uuid.Nil {
|
||||
t.Fatalf("C1 scope = %s %v %s, want none", personalData.OrganizationID(), personalData.Fields().Fields(), personalData.InvitationID())
|
||||
}
|
||||
if _, revoked := personalData.RevokedAt(); revoked || personalData.State() != domain.ConsentStateActive {
|
||||
t.Fatalf("C1 state = %s, want active and unrevoked", personalData.State())
|
||||
}
|
||||
|
||||
// A row changed outside the application fails instead of producing a
|
||||
// record that breaks the ledger rules.
|
||||
if _, err := consentRecordFromRow(consentRecordRow{
|
||||
ID: pgUUID(uuid.Must(uuid.NewV7())), SubjectID: pgUUID(subject), Purpose: "c2", TextVersion: "c2-2026-10-01",
|
||||
TextHash: hash[:], Source: "consent_settings", OrganizationID: pgUUID(organization), GrantedAt: pgTime(grantedAt), State: "active",
|
||||
}); !errors.Is(err, domain.ErrInvalidConsent) {
|
||||
t.Fatalf("consentRecordFromRow(C2 with an organization) error = %v, want ErrInvalidConsent", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestContactFieldStringsKeepsCanonicalOrder(t *testing.T) {
|
||||
set, err := domain.NewContactFieldSet(domain.ContactFieldTelegram, domain.ContactFieldFullName, domain.ContactFieldEmail)
|
||||
if err != nil {
|
||||
t.Fatalf("NewContactFieldSet() error = %v", err)
|
||||
}
|
||||
// The migration's consent_field_set_is_canonical accepts only ascending
|
||||
// byte order, the order of PostgreSQL's "C" collation.
|
||||
if got, want := strings.Join(contactFieldStrings(set), ","), "email,full_name,telegram"; got != want {
|
||||
t.Fatalf("contactFieldStrings() = %s, want %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapCleanupErrorReportsAConcurrentConsentAsARetryableConflict(t *testing.T) {
|
||||
concurrent := mapCleanupError(&pgconn.PgError{Code: restrictViolationCode, ConstraintName: consentSubjectForeignKey, Detail: consentDetailMarker})
|
||||
if !errors.Is(concurrent, outbound.ErrTransactionConflict) || strings.Contains(concurrent.Error(), "subject_id)=") {
|
||||
t.Fatalf("mapCleanupError(restrict) = %v, want ErrTransactionConflict without the detail", concurrent)
|
||||
}
|
||||
// Another restricting key, or the same key with another code, is no
|
||||
// conflict.
|
||||
for _, original := range []*pgconn.PgError{
|
||||
{Code: restrictViolationCode, ConstraintName: "other_fkey"},
|
||||
{Code: foreignKeyViolationCode, ConstraintName: consentSubjectForeignKey},
|
||||
} {
|
||||
if err := mapCleanupError(original); errors.Is(err, outbound.ErrTransactionConflict) {
|
||||
t.Fatalf("mapCleanupError(%s %s) = %v, want no conflict", original.Code, original.ConstraintName, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,11 @@ import (
|
||||
|
||||
const (
|
||||
foreignKeyViolationCode = "23503"
|
||||
// restrictViolationCode is raised by an ON DELETE RESTRICT foreign key.
|
||||
restrictViolationCode = "23001"
|
||||
// consentSubjectForeignKey restricts the delete of an account with
|
||||
// consent records.
|
||||
consentSubjectForeignKey = "consent_records_subject_id_fkey"
|
||||
|
||||
// sessionTouchInterval is the minimum age of last_seen_at before Touch
|
||||
// writes it again. It bounds session writes to one per minute per session
|
||||
@@ -216,7 +221,9 @@ func (repository userRepository) UpdateRegistration(ctx context.Context, user do
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("userRepository.UpdateRegistration - update user: %w", mapNoRows(err, outbound.ErrUserVersionConflict))
|
||||
}
|
||||
return userFromRow(row)
|
||||
// The statement returns the users columns through a CTE, so sqlc gives
|
||||
// it its own row type with the same fields.
|
||||
return userFromRow(sqlc.User(row))
|
||||
}
|
||||
|
||||
func (repository userRepository) MarkEmailVerified(
|
||||
@@ -251,11 +258,26 @@ func (repository userRepository) DeleteUnverifiedRegisteredBefore(ctx context.Co
|
||||
BatchLimit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("userRepository.DeleteUnverifiedRegisteredBefore - delete users: %w", mapIdentityError(err))
|
||||
return 0, fmt.Errorf("userRepository.DeleteUnverifiedRegisteredBefore - delete users: %w", mapCleanupError(err))
|
||||
}
|
||||
return deleted, nil
|
||||
}
|
||||
|
||||
// mapCleanupError reports the restricting consent foreign key as a
|
||||
// transaction conflict. The cleanup checks consent rows in its statement
|
||||
// snapshot, so a consent committed for a candidate account after the
|
||||
// snapshot but before the account lock passes that check and then fails
|
||||
// the foreign key at the end of the statement. Nothing was deleted, and the
|
||||
// next run sees the consent and skips or removes the account.
|
||||
func mapCleanupError(err error) error {
|
||||
var pgError *pgconn.PgError
|
||||
if errors.As(err, &pgError) && pgError.Code == restrictViolationCode && pgError.ConstraintName == consentSubjectForeignKey {
|
||||
return fmt.Errorf("postgres.mapCleanupError - consent recorded concurrently: %w: %w",
|
||||
outbound.ErrTransactionConflict, &databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
|
||||
}
|
||||
return mapIdentityError(err)
|
||||
}
|
||||
|
||||
func userFromRow(row sqlc.User) (domain.User, error) {
|
||||
email, err := domain.RestoreEmailAddress(row.Email, row.EmailNormalized)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,961 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: consents.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getConsentText = `-- name: GetConsentText :one
|
||||
SELECT
|
||||
purpose,
|
||||
version,
|
||||
body,
|
||||
body_sha256,
|
||||
kind,
|
||||
published_at
|
||||
FROM consent_texts
|
||||
WHERE
|
||||
purpose = $1
|
||||
AND version = $2
|
||||
`
|
||||
|
||||
type GetConsentTextParams struct {
|
||||
Purpose string
|
||||
Version string
|
||||
}
|
||||
|
||||
func (q *Queries) GetConsentText(ctx context.Context, arg GetConsentTextParams) (ConsentText, error) {
|
||||
row := q.db.QueryRow(ctx, getConsentText, arg.Purpose, arg.Version)
|
||||
var i ConsentText
|
||||
err := row.Scan(
|
||||
&i.Purpose,
|
||||
&i.Version,
|
||||
&i.Body,
|
||||
&i.BodySha256,
|
||||
&i.Kind,
|
||||
&i.PublishedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getContactConsentRecordByInvitation = `-- name: GetContactConsentRecordByInvitation :one
|
||||
SELECT
|
||||
id,
|
||||
subject_id,
|
||||
purpose,
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
invitation_id,
|
||||
invitation_terms_version,
|
||||
granted_at,
|
||||
revoked_at,
|
||||
revocation_source,
|
||||
(
|
||||
CASE WHEN revoked_at IS NULL THEN 'active' ELSE 'revoked' END
|
||||
)::text AS state
|
||||
FROM consent_records
|
||||
WHERE
|
||||
subject_id = $1
|
||||
AND invitation_id = $2
|
||||
`
|
||||
|
||||
type GetContactConsentRecordByInvitationParams struct {
|
||||
SubjectID pgtype.UUID
|
||||
InvitationID pgtype.UUID
|
||||
}
|
||||
|
||||
type GetContactConsentRecordByInvitationRow struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
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 (q *Queries) GetContactConsentRecordByInvitation(ctx context.Context, arg GetContactConsentRecordByInvitationParams) (GetContactConsentRecordByInvitationRow, error) {
|
||||
row := q.db.QueryRow(ctx, getContactConsentRecordByInvitation, arg.SubjectID, arg.InvitationID)
|
||||
var i GetContactConsentRecordByInvitationRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.SubjectID,
|
||||
&i.Purpose,
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
&i.InvitationID,
|
||||
&i.InvitationTermsVersion,
|
||||
&i.GrantedAt,
|
||||
&i.RevokedAt,
|
||||
&i.RevocationSource,
|
||||
&i.State,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getCurrentConsentRecord = `-- name: GetCurrentConsentRecord :one
|
||||
SELECT
|
||||
id,
|
||||
subject_id,
|
||||
purpose,
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
invitation_id,
|
||||
invitation_terms_version,
|
||||
granted_at,
|
||||
revoked_at,
|
||||
revocation_source,
|
||||
'active'::text AS state
|
||||
FROM consent_records
|
||||
WHERE
|
||||
subject_id = $1
|
||||
AND purpose = $2
|
||||
AND purpose <> 'c4'
|
||||
AND revoked_at IS NULL
|
||||
ORDER BY granted_at DESC, id DESC
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
type GetCurrentConsentRecordParams struct {
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
}
|
||||
|
||||
type GetCurrentConsentRecordRow struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
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
|
||||
}
|
||||
|
||||
// The newest unrevoked record of a purpose other than C4.
|
||||
func (q *Queries) GetCurrentConsentRecord(ctx context.Context, arg GetCurrentConsentRecordParams) (GetCurrentConsentRecordRow, error) {
|
||||
row := q.db.QueryRow(ctx, getCurrentConsentRecord, arg.SubjectID, arg.Purpose)
|
||||
var i GetCurrentConsentRecordRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.SubjectID,
|
||||
&i.Purpose,
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
&i.InvitationID,
|
||||
&i.InvitationTermsVersion,
|
||||
&i.GrantedAt,
|
||||
&i.RevokedAt,
|
||||
&i.RevocationSource,
|
||||
&i.State,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getCurrentConsentText = `-- name: GetCurrentConsentText :one
|
||||
SELECT
|
||||
purpose,
|
||||
version,
|
||||
body,
|
||||
body_sha256,
|
||||
kind,
|
||||
published_at
|
||||
FROM consent_texts
|
||||
WHERE
|
||||
purpose = $1
|
||||
AND published_at <= $2
|
||||
ORDER BY published_at DESC
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
type GetCurrentConsentTextParams struct {
|
||||
Purpose string
|
||||
At pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// The text of a purpose that applies at a time: the latest publication not
|
||||
// after it.
|
||||
func (q *Queries) GetCurrentConsentText(ctx context.Context, arg GetCurrentConsentTextParams) (ConsentText, error) {
|
||||
row := q.db.QueryRow(ctx, getCurrentConsentText, arg.Purpose, arg.At)
|
||||
var i ConsentText
|
||||
err := row.Scan(
|
||||
&i.Purpose,
|
||||
&i.Version,
|
||||
&i.Body,
|
||||
&i.BodySha256,
|
||||
&i.Kind,
|
||||
&i.PublishedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUnrevokedConsentRecordByVersion = `-- name: GetUnrevokedConsentRecordByVersion :one
|
||||
SELECT
|
||||
record.id,
|
||||
record.subject_id,
|
||||
record.purpose,
|
||||
record.text_version,
|
||||
record.text_hash,
|
||||
record.source,
|
||||
record.organization_id,
|
||||
record.organization_name,
|
||||
record.field_set,
|
||||
record.invitation_id,
|
||||
record.invitation_terms_version,
|
||||
record.granted_at,
|
||||
record.revoked_at,
|
||||
record.revocation_source,
|
||||
(
|
||||
CASE
|
||||
WHEN exists(
|
||||
SELECT 1 FROM consent_records AS newer
|
||||
WHERE
|
||||
newer.subject_id = record.subject_id
|
||||
AND newer.purpose = record.purpose
|
||||
AND newer.revoked_at IS NULL
|
||||
AND (newer.granted_at, newer.id)
|
||||
> (record.granted_at, record.id)
|
||||
) THEN 'superseded'
|
||||
ELSE 'active'
|
||||
END
|
||||
)::text AS state
|
||||
FROM consent_records AS record
|
||||
WHERE
|
||||
record.subject_id = $1
|
||||
AND record.purpose = $2
|
||||
AND record.text_version = $3
|
||||
AND record.revoked_at IS NULL
|
||||
`
|
||||
|
||||
type GetUnrevokedConsentRecordByVersionParams struct {
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
}
|
||||
|
||||
type GetUnrevokedConsentRecordByVersionRow struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
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 (q *Queries) GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error) {
|
||||
row := q.db.QueryRow(ctx, getUnrevokedConsentRecordByVersion, arg.SubjectID, arg.Purpose, arg.TextVersion)
|
||||
var i GetUnrevokedConsentRecordByVersionRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.SubjectID,
|
||||
&i.Purpose,
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
&i.InvitationID,
|
||||
&i.InvitationTermsVersion,
|
||||
&i.GrantedAt,
|
||||
&i.RevokedAt,
|
||||
&i.RevocationSource,
|
||||
&i.State,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertConsentRecord = `-- name: InsertConsentRecord :one
|
||||
INSERT INTO consent_records (
|
||||
id,
|
||||
subject_id,
|
||||
purpose,
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
granted_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7
|
||||
)
|
||||
ON CONFLICT (subject_id, purpose, text_version)
|
||||
WHERE revoked_at IS NULL AND purpose <> 'c4'
|
||||
DO NOTHING
|
||||
RETURNING
|
||||
id,
|
||||
subject_id,
|
||||
purpose,
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
invitation_id,
|
||||
invitation_terms_version,
|
||||
granted_at,
|
||||
revoked_at,
|
||||
revocation_source,
|
||||
(
|
||||
CASE
|
||||
WHEN exists(
|
||||
SELECT 1 FROM consent_records AS newer
|
||||
WHERE
|
||||
newer.subject_id = consent_records.subject_id
|
||||
AND newer.purpose = consent_records.purpose
|
||||
AND newer.revoked_at IS NULL
|
||||
AND (newer.granted_at, newer.id)
|
||||
> (consent_records.granted_at, consent_records.id)
|
||||
) THEN 'superseded'
|
||||
ELSE 'active'
|
||||
END
|
||||
)::text AS state
|
||||
`
|
||||
|
||||
type InsertConsentRecordParams struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
GrantedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type InsertConsentRecordRow struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
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
|
||||
}
|
||||
|
||||
// Records a grant of C1, C2, C3, or C5. An unrevoked record of the same
|
||||
// subject, purpose, and text version already exists when no row returns;
|
||||
// the insert then changes nothing and does not abort the transaction.
|
||||
func (q *Queries) InsertConsentRecord(ctx context.Context, arg InsertConsentRecordParams) (InsertConsentRecordRow, error) {
|
||||
row := q.db.QueryRow(ctx, insertConsentRecord,
|
||||
arg.ID,
|
||||
arg.SubjectID,
|
||||
arg.Purpose,
|
||||
arg.TextVersion,
|
||||
arg.TextHash,
|
||||
arg.Source,
|
||||
arg.GrantedAt,
|
||||
)
|
||||
var i InsertConsentRecordRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.SubjectID,
|
||||
&i.Purpose,
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
&i.InvitationID,
|
||||
&i.InvitationTermsVersion,
|
||||
&i.GrantedAt,
|
||||
&i.RevokedAt,
|
||||
&i.RevocationSource,
|
||||
&i.State,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertContactConsentRecord = `-- name: InsertContactConsentRecord :one
|
||||
INSERT INTO consent_records (
|
||||
id,
|
||||
subject_id,
|
||||
purpose,
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
invitation_id,
|
||||
invitation_terms_version,
|
||||
granted_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
'c4',
|
||||
$3,
|
||||
$4,
|
||||
'invitation_acceptance',
|
||||
$5,
|
||||
$6,
|
||||
$7::text [],
|
||||
$8,
|
||||
$9,
|
||||
$10
|
||||
)
|
||||
ON CONFLICT (invitation_id) WHERE invitation_id IS NOT NULL
|
||||
DO NOTHING
|
||||
RETURNING
|
||||
id,
|
||||
subject_id,
|
||||
purpose,
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
invitation_id,
|
||||
invitation_terms_version,
|
||||
granted_at,
|
||||
revoked_at,
|
||||
revocation_source,
|
||||
'active'::text AS state
|
||||
`
|
||||
|
||||
type InsertContactConsentRecordParams struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
InvitationID pgtype.UUID
|
||||
InvitationTermsVersion pgtype.Int8
|
||||
GrantedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type InsertContactConsentRecordRow struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
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
|
||||
}
|
||||
|
||||
// Records a C4 grant with its scope. The invitation already has a C4 record
|
||||
// when no row returns; the insert then changes nothing and does not abort
|
||||
// the transaction.
|
||||
func (q *Queries) InsertContactConsentRecord(ctx context.Context, arg InsertContactConsentRecordParams) (InsertContactConsentRecordRow, error) {
|
||||
row := q.db.QueryRow(ctx, insertContactConsentRecord,
|
||||
arg.ID,
|
||||
arg.SubjectID,
|
||||
arg.TextVersion,
|
||||
arg.TextHash,
|
||||
arg.OrganizationID,
|
||||
arg.OrganizationName,
|
||||
arg.FieldSet,
|
||||
arg.InvitationID,
|
||||
arg.InvitationTermsVersion,
|
||||
arg.GrantedAt,
|
||||
)
|
||||
var i InsertContactConsentRecordRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.SubjectID,
|
||||
&i.Purpose,
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
&i.InvitationID,
|
||||
&i.InvitationTermsVersion,
|
||||
&i.GrantedAt,
|
||||
&i.RevokedAt,
|
||||
&i.RevocationSource,
|
||||
&i.State,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listConsentRecords = `-- name: ListConsentRecords :many
|
||||
WITH ledger AS (
|
||||
SELECT
|
||||
record.id,
|
||||
record.subject_id,
|
||||
record.purpose,
|
||||
record.text_version,
|
||||
record.text_hash,
|
||||
record.source,
|
||||
record.organization_id,
|
||||
record.organization_name,
|
||||
record.field_set,
|
||||
record.invitation_id,
|
||||
record.invitation_terms_version,
|
||||
record.granted_at,
|
||||
record.revoked_at,
|
||||
record.revocation_source,
|
||||
(
|
||||
CASE
|
||||
WHEN record.revoked_at IS NOT NULL THEN 'revoked'
|
||||
WHEN record.purpose <> 'c4' AND exists(
|
||||
SELECT 1 FROM consent_records AS newer
|
||||
WHERE
|
||||
newer.subject_id = record.subject_id
|
||||
AND newer.purpose = record.purpose
|
||||
AND newer.revoked_at IS NULL
|
||||
AND (newer.granted_at, newer.id)
|
||||
> (record.granted_at, record.id)
|
||||
) THEN 'superseded'
|
||||
ELSE 'active'
|
||||
END
|
||||
)::text AS state
|
||||
FROM consent_records AS record
|
||||
WHERE record.subject_id = $5
|
||||
)
|
||||
|
||||
SELECT
|
||||
ledger.id,
|
||||
ledger.subject_id,
|
||||
ledger.purpose,
|
||||
ledger.text_version,
|
||||
ledger.text_hash,
|
||||
ledger.source,
|
||||
ledger.organization_id,
|
||||
ledger.organization_name,
|
||||
ledger.field_set,
|
||||
ledger.invitation_id,
|
||||
ledger.invitation_terms_version,
|
||||
ledger.granted_at,
|
||||
ledger.revoked_at,
|
||||
ledger.revocation_source,
|
||||
ledger.state
|
||||
FROM ledger
|
||||
WHERE
|
||||
($1::text IS NULL OR ledger.state = $1::text)
|
||||
AND (
|
||||
$2::timestamptz IS NULL
|
||||
OR (ledger.granted_at, ledger.id) < (
|
||||
$2::timestamptz,
|
||||
$3::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY ledger.granted_at DESC, ledger.id DESC
|
||||
LIMIT $4
|
||||
`
|
||||
|
||||
type ListConsentRecordsParams struct {
|
||||
State pgtype.Text
|
||||
AfterGrantedAt pgtype.Timestamptz
|
||||
AfterID pgtype.UUID
|
||||
RowLimit int32
|
||||
SubjectID pgtype.UUID
|
||||
}
|
||||
|
||||
type ListConsentRecordsRow struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
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
|
||||
}
|
||||
|
||||
// One page of the subject's ledger, newest grant first, optionally limited
|
||||
// to one state. Every record query is scoped by the subject, so a caller
|
||||
// never reads or revokes another subject's consent. The state is computed,
|
||||
// never stored: revoked once revoked_at is set; superseded when a newer
|
||||
// unrevoked record of the same subject and purpose exists (never for C4,
|
||||
// whose records are scoped by invitation); active otherwise. The page continues after the (granted_at, id) position of
|
||||
// the last record of the previous page.
|
||||
func (q *Queries) ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listConsentRecords,
|
||||
arg.State,
|
||||
arg.AfterGrantedAt,
|
||||
arg.AfterID,
|
||||
arg.RowLimit,
|
||||
arg.SubjectID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListConsentRecordsRow
|
||||
for rows.Next() {
|
||||
var i ListConsentRecordsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.SubjectID,
|
||||
&i.Purpose,
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
&i.InvitationID,
|
||||
&i.InvitationTermsVersion,
|
||||
&i.GrantedAt,
|
||||
&i.RevokedAt,
|
||||
&i.RevocationSource,
|
||||
&i.State,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listCurrentContactConsentRecords = `-- name: ListCurrentContactConsentRecords :many
|
||||
SELECT
|
||||
id,
|
||||
subject_id,
|
||||
purpose,
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
invitation_id,
|
||||
invitation_terms_version,
|
||||
granted_at,
|
||||
revoked_at,
|
||||
revocation_source,
|
||||
'active'::text AS state
|
||||
FROM consent_records
|
||||
WHERE
|
||||
subject_id = $1
|
||||
AND purpose = 'c4'
|
||||
AND organization_id = $2
|
||||
AND revoked_at IS NULL
|
||||
ORDER BY granted_at DESC, id DESC
|
||||
`
|
||||
|
||||
type ListCurrentContactConsentRecordsParams struct {
|
||||
SubjectID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
}
|
||||
|
||||
type ListCurrentContactConsentRecordsRow struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
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 (q *Queries) ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCurrentContactConsentRecords, arg.SubjectID, arg.OrganizationID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCurrentContactConsentRecordsRow
|
||||
for rows.Next() {
|
||||
var i ListCurrentContactConsentRecordsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.SubjectID,
|
||||
&i.Purpose,
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
&i.InvitationID,
|
||||
&i.InvitationTermsVersion,
|
||||
&i.GrantedAt,
|
||||
&i.RevokedAt,
|
||||
&i.RevocationSource,
|
||||
&i.State,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const revokeConsentRecords = `-- name: RevokeConsentRecords :many
|
||||
UPDATE consent_records
|
||||
SET
|
||||
revoked_at = greatest($1::timestamptz, granted_at),
|
||||
revocation_source = $2
|
||||
WHERE
|
||||
subject_id = $3
|
||||
AND purpose = $4
|
||||
AND purpose <> 'c4'
|
||||
AND revoked_at IS NULL
|
||||
RETURNING
|
||||
id,
|
||||
subject_id,
|
||||
purpose,
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
invitation_id,
|
||||
invitation_terms_version,
|
||||
granted_at,
|
||||
revoked_at,
|
||||
revocation_source,
|
||||
'revoked'::text AS state
|
||||
`
|
||||
|
||||
type RevokeConsentRecordsParams struct {
|
||||
RevokedAt pgtype.Timestamptz
|
||||
RevocationSource pgtype.Text
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
}
|
||||
|
||||
type RevokeConsentRecordsRow struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
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
|
||||
}
|
||||
|
||||
// Revokes every unrevoked record of a purpose other than C4, superseded ones
|
||||
// included, and returns them. A revocation time before the grant time, from
|
||||
// clock skew between instances, is stamped at the grant time instead.
|
||||
func (q *Queries) RevokeConsentRecords(ctx context.Context, arg RevokeConsentRecordsParams) ([]RevokeConsentRecordsRow, error) {
|
||||
rows, err := q.db.Query(ctx, revokeConsentRecords,
|
||||
arg.RevokedAt,
|
||||
arg.RevocationSource,
|
||||
arg.SubjectID,
|
||||
arg.Purpose,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []RevokeConsentRecordsRow
|
||||
for rows.Next() {
|
||||
var i RevokeConsentRecordsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.SubjectID,
|
||||
&i.Purpose,
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
&i.InvitationID,
|
||||
&i.InvitationTermsVersion,
|
||||
&i.GrantedAt,
|
||||
&i.RevokedAt,
|
||||
&i.RevocationSource,
|
||||
&i.State,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const revokeContactConsentRecords = `-- name: RevokeContactConsentRecords :many
|
||||
UPDATE consent_records
|
||||
SET
|
||||
revoked_at = greatest($1::timestamptz, granted_at),
|
||||
revocation_source = $2
|
||||
WHERE
|
||||
subject_id = $3
|
||||
AND purpose = 'c4'
|
||||
AND organization_id = $4
|
||||
AND revoked_at IS NULL
|
||||
RETURNING
|
||||
id,
|
||||
subject_id,
|
||||
purpose,
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
invitation_id,
|
||||
invitation_terms_version,
|
||||
granted_at,
|
||||
revoked_at,
|
||||
revocation_source,
|
||||
'revoked'::text AS state
|
||||
`
|
||||
|
||||
type RevokeContactConsentRecordsParams struct {
|
||||
RevokedAt pgtype.Timestamptz
|
||||
RevocationSource pgtype.Text
|
||||
SubjectID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
}
|
||||
|
||||
type RevokeContactConsentRecordsRow struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
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
|
||||
}
|
||||
|
||||
// Revokes every unrevoked C4 record of the subject for one organization and
|
||||
// returns them, with the same clamp of the revocation time as above.
|
||||
func (q *Queries) RevokeContactConsentRecords(ctx context.Context, arg RevokeContactConsentRecordsParams) ([]RevokeContactConsentRecordsRow, error) {
|
||||
rows, err := q.db.Query(ctx, revokeContactConsentRecords,
|
||||
arg.RevokedAt,
|
||||
arg.RevocationSource,
|
||||
arg.SubjectID,
|
||||
arg.OrganizationID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []RevokeContactConsentRecordsRow
|
||||
for rows.Next() {
|
||||
var i RevokeContactConsentRecordsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.SubjectID,
|
||||
&i.Purpose,
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
&i.InvitationID,
|
||||
&i.InvitationTermsVersion,
|
||||
&i.GrantedAt,
|
||||
&i.RevokedAt,
|
||||
&i.RevocationSource,
|
||||
&i.State,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -107,6 +107,13 @@ locked_delivery AS (
|
||||
FOR UPDATE SKIP LOCKED
|
||||
),
|
||||
|
||||
locked_consent AS (
|
||||
SELECT consent.subject_id
|
||||
FROM consent_records AS consent
|
||||
WHERE consent.subject_id IN (SELECT candidate.id FROM candidate)
|
||||
FOR UPDATE SKIP LOCKED
|
||||
),
|
||||
|
||||
deletable AS (
|
||||
SELECT candidate.id
|
||||
FROM candidate
|
||||
@@ -139,6 +146,19 @@ deletable AS (
|
||||
SELECT count(*) FROM locked_delivery
|
||||
WHERE locked_delivery.recipient_user_id = candidate.id
|
||||
)
|
||||
AND (
|
||||
SELECT count(*) FROM consent_records AS consent
|
||||
WHERE consent.subject_id = candidate.id
|
||||
) = (
|
||||
SELECT count(*) FROM locked_consent
|
||||
WHERE locked_consent.subject_id = candidate.id
|
||||
)
|
||||
),
|
||||
|
||||
deleted_consent AS (
|
||||
DELETE FROM consent_records
|
||||
USING deletable
|
||||
WHERE consent_records.subject_id = deletable.id
|
||||
)
|
||||
|
||||
DELETE FROM users
|
||||
@@ -152,18 +172,23 @@ type DeleteUnverifiedUsersRegisteredBeforeParams struct {
|
||||
}
|
||||
|
||||
// Deletes one batch of accounts that stayed unverified since before cutoff,
|
||||
// oldest first, with their tokens, sessions, mail requests, and mail
|
||||
// deliveries (and through the deliveries their attempts). Every lock is taken
|
||||
// oldest first, with their tokens, sessions, mail requests, mail deliveries
|
||||
// (and through the deliveries their attempts), and consent records. The
|
||||
// consent records reference the account with ON DELETE RESTRICT, so they are
|
||||
// deleted explicitly in the same statement: a registration never confirmed
|
||||
// by its email owner is not kept as consent evidence. Every lock is taken
|
||||
// with SKIP LOCKED, so the statement never waits: an account whose row is
|
||||
// locked, for example by a re-registration, a token insert, or a delivery
|
||||
// insert, is skipped, and so is an account with any token, session, mail
|
||||
// request, or delivery row locked, for example by a confirmation that
|
||||
// consumed a token, the delivery consumer, or a worker recording an attempt.
|
||||
// Skipped accounts stay for the next run.
|
||||
// locked, for example by a re-registration, a token insert, a delivery
|
||||
// insert, or a consent insert, is skipped, and so is an account with any
|
||||
// token, session, mail request, delivery, or consent row locked, for example
|
||||
// by a confirmation that consumed a token, the delivery consumer, or a
|
||||
// worker recording an attempt. Skipped accounts stay for the next run.
|
||||
// Taking the account lock before the token locks is the reverse of the
|
||||
// documented order, which is safe only because no lock here waits.
|
||||
// An account qualifies only when every token, session, mail request, and
|
||||
// delivery row visible to the statement was locked above.
|
||||
// An account qualifies only when every token, session, mail request,
|
||||
// delivery, and consent row visible to the statement was locked above.
|
||||
// The restricting foreign key is checked at the end of the statement, after
|
||||
// these rows are gone.
|
||||
func (q *Queries) DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, deleteUnverifiedUsersRegisteredBefore, arg.Cutoff, arg.BatchLimit)
|
||||
if err != nil {
|
||||
@@ -646,33 +671,59 @@ func (q *Queries) TouchSession(ctx context.Context, arg TouchSessionParams) (Tou
|
||||
}
|
||||
|
||||
const updateUserRegistration = `-- name: UpdateUserRegistration :one
|
||||
UPDATE users
|
||||
SET
|
||||
email = $1,
|
||||
password_hash = $2,
|
||||
scenario = $3,
|
||||
onboarding_step = $4,
|
||||
registration_version = registration_version + 1,
|
||||
last_registered_at = $5,
|
||||
updated_at = $6,
|
||||
version = version + 1
|
||||
WHERE
|
||||
id = $7
|
||||
AND version = $8
|
||||
AND email_verified_at IS NULL
|
||||
RETURNING
|
||||
id,
|
||||
email,
|
||||
email_normalized,
|
||||
password_hash,
|
||||
scenario,
|
||||
onboarding_step,
|
||||
email_verified_at,
|
||||
registration_version,
|
||||
last_registered_at,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
WITH updated AS (
|
||||
UPDATE users
|
||||
SET
|
||||
email = $1,
|
||||
password_hash = $2,
|
||||
scenario = $3,
|
||||
onboarding_step = $4,
|
||||
registration_version = registration_version + 1,
|
||||
last_registered_at = $5,
|
||||
updated_at = $6,
|
||||
version = version + 1
|
||||
WHERE
|
||||
users.id = $7
|
||||
AND users.version = $8
|
||||
AND users.email_verified_at IS NULL
|
||||
RETURNING
|
||||
users.id,
|
||||
users.email,
|
||||
users.email_normalized,
|
||||
users.password_hash,
|
||||
users.scenario,
|
||||
users.onboarding_step,
|
||||
users.email_verified_at,
|
||||
users.registration_version,
|
||||
users.last_registered_at,
|
||||
users.version,
|
||||
users.created_at,
|
||||
users.updated_at
|
||||
),
|
||||
|
||||
discarded_consent AS (
|
||||
DELETE FROM consent_records
|
||||
USING updated
|
||||
WHERE
|
||||
consent_records.subject_id = updated.id
|
||||
AND consent_records.purpose = 'c1'
|
||||
AND consent_records.source = 'registration'
|
||||
)
|
||||
|
||||
SELECT
|
||||
updated.id,
|
||||
updated.email,
|
||||
updated.email_normalized,
|
||||
updated.password_hash,
|
||||
updated.scenario,
|
||||
updated.onboarding_step,
|
||||
updated.email_verified_at,
|
||||
updated.registration_version,
|
||||
updated.last_registered_at,
|
||||
updated.version,
|
||||
updated.created_at,
|
||||
updated.updated_at
|
||||
FROM updated
|
||||
`
|
||||
|
||||
type UpdateUserRegistrationParams struct {
|
||||
@@ -686,11 +737,29 @@ type UpdateUserRegistrationParams struct {
|
||||
ExpectedVersion int64
|
||||
}
|
||||
|
||||
type UpdateUserRegistrationRow struct {
|
||||
ID pgtype.UUID
|
||||
Email string
|
||||
EmailNormalized string
|
||||
PasswordHash string
|
||||
Scenario string
|
||||
OnboardingStep string
|
||||
EmailVerifiedAt pgtype.Timestamptz
|
||||
RegistrationVersion int64
|
||||
LastRegisteredAt pgtype.Timestamptz
|
||||
Version int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Replaces the registration of an unverified account and advances the
|
||||
// registration version in the same statement, so no caller can choose it.
|
||||
// The version check rejects a writer that read an older row; a verified
|
||||
// account never changes.
|
||||
func (q *Queries) UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (User, error) {
|
||||
// account never changes. The same statement deletes the C1 that the earlier
|
||||
// registration of this account recorded, so the consent of an earlier
|
||||
// registrant never stands for the new one; the new registration records its
|
||||
// own C1 in the same transaction. A version conflict deletes nothing.
|
||||
func (q *Queries) UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (UpdateUserRegistrationRow, error) {
|
||||
row := q.db.QueryRow(ctx, updateUserRegistration,
|
||||
arg.Email,
|
||||
arg.PasswordHash,
|
||||
@@ -701,7 +770,7 @@ func (q *Queries) UpdateUserRegistration(ctx context.Context, arg UpdateUserRegi
|
||||
arg.ID,
|
||||
arg.ExpectedVersion,
|
||||
)
|
||||
var i User
|
||||
var i UpdateUserRegistrationRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Email,
|
||||
|
||||
@@ -8,6 +8,33 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type ConsentRecord struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
PublishedTextHash []byte
|
||||
Source string
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
InvitationID pgtype.UUID
|
||||
InvitationTermsVersion pgtype.Int8
|
||||
GrantedAt pgtype.Timestamptz
|
||||
RevokedAt pgtype.Timestamptz
|
||||
RevocationSource pgtype.Text
|
||||
}
|
||||
|
||||
type ConsentText struct {
|
||||
Purpose string
|
||||
Version string
|
||||
Body string
|
||||
BodySha256 []byte
|
||||
Kind string
|
||||
PublishedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type ConsumerDeadLetter struct {
|
||||
ID int64
|
||||
ConsumerName string
|
||||
|
||||
@@ -50,18 +50,23 @@ type Querier interface {
|
||||
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error)
|
||||
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
|
||||
// Deletes one batch of accounts that stayed unverified since before cutoff,
|
||||
// oldest first, with their tokens, sessions, mail requests, and mail
|
||||
// deliveries (and through the deliveries their attempts). Every lock is taken
|
||||
// oldest first, with their tokens, sessions, mail requests, mail deliveries
|
||||
// (and through the deliveries their attempts), and consent records. The
|
||||
// consent records reference the account with ON DELETE RESTRICT, so they are
|
||||
// deleted explicitly in the same statement: a registration never confirmed
|
||||
// by its email owner is not kept as consent evidence. Every lock is taken
|
||||
// with SKIP LOCKED, so the statement never waits: an account whose row is
|
||||
// locked, for example by a re-registration, a token insert, or a delivery
|
||||
// insert, is skipped, and so is an account with any token, session, mail
|
||||
// request, or delivery row locked, for example by a confirmation that
|
||||
// consumed a token, the delivery consumer, or a worker recording an attempt.
|
||||
// Skipped accounts stay for the next run.
|
||||
// locked, for example by a re-registration, a token insert, a delivery
|
||||
// insert, or a consent insert, is skipped, and so is an account with any
|
||||
// token, session, mail request, delivery, or consent row locked, for example
|
||||
// by a confirmation that consumed a token, the delivery consumer, or a
|
||||
// worker recording an attempt. Skipped accounts stay for the next run.
|
||||
// Taking the account lock before the token locks is the reverse of the
|
||||
// documented order, which is safe only because no lock here waits.
|
||||
// An account qualifies only when every token, session, mail request, and
|
||||
// delivery row visible to the statement was locked above.
|
||||
// An account qualifies only when every token, session, mail request,
|
||||
// delivery, and consent row visible to the statement was locked above.
|
||||
// The restricting foreign key is checked at the end of the statement, after
|
||||
// these rows are gone.
|
||||
DeleteUnverifiedUsersRegisteredBefore(ctx context.Context, arg DeleteUnverifiedUsersRegisteredBeforeParams) (int64, error)
|
||||
// Lock order. Every transaction that writes mail_quota_usage first creates
|
||||
// and locks all the usage rows it will touch with EnsureMailQuotaRows and
|
||||
@@ -85,6 +90,13 @@ type Querier interface {
|
||||
// provider's idempotency window reuses it instead of counting again.
|
||||
FindOpenMailQuotaReservation(ctx context.Context, arg FindOpenMailQuotaReservationParams) (FindOpenMailQuotaReservationRow, error)
|
||||
GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error)
|
||||
GetConsentText(ctx context.Context, arg GetConsentTextParams) (ConsentText, error)
|
||||
GetContactConsentRecordByInvitation(ctx context.Context, arg GetContactConsentRecordByInvitationParams) (GetContactConsentRecordByInvitationRow, error)
|
||||
// The newest unrevoked record of a purpose other than C4.
|
||||
GetCurrentConsentRecord(ctx context.Context, arg GetCurrentConsentRecordParams) (GetCurrentConsentRecordRow, error)
|
||||
// The text of a purpose that applies at a time: the latest publication not
|
||||
// after it.
|
||||
GetCurrentConsentText(ctx context.Context, arg GetCurrentConsentTextParams) (ConsentText, error)
|
||||
GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error)
|
||||
// Among the versions of a family already effective at a time, the newest
|
||||
// publication wins. A version scheduled for later therefore never undoes a
|
||||
@@ -116,13 +128,22 @@ type Querier interface {
|
||||
// the handler transaction that holds its row lock: only that transaction
|
||||
// can have changed it, for example by canceling its own job.
|
||||
GetScheduledJobStatus(ctx context.Context, id int64) (string, error)
|
||||
GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error)
|
||||
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
|
||||
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
|
||||
// Records a grant of C1, C2, C3, or C5. An unrevoked record of the same
|
||||
// subject, purpose, and text version already exists when no row returns;
|
||||
// the insert then changes nothing and does not abort the transaction.
|
||||
InsertConsentRecord(ctx context.Context, arg InsertConsentRecordParams) (InsertConsentRecordRow, error)
|
||||
// Stores a record that a consumer could not apply. A second delivery of the
|
||||
// same record (same position and value) refreshes the outcome of its row:
|
||||
// after a rewind the handler may fail differently. A different value at a
|
||||
// reused position, after the topic was recreated, gets its own row.
|
||||
InsertConsumerDeadLetter(ctx context.Context, arg InsertConsumerDeadLetterParams) error
|
||||
// Records a C4 grant with its scope. The invitation already has a C4 record
|
||||
// when no row returns; the insert then changes nothing and does not abort
|
||||
// the transaction.
|
||||
InsertContactConsentRecord(ctx context.Context, arg InsertContactConsentRecordParams) (InsertContactConsentRecordRow, error)
|
||||
// Stores a new delivery. A delivery with the same ID already exists when the
|
||||
// same request is handled again; the statement then inserts nothing and
|
||||
// returns 0 rows, and the stored content stays as it was. While another
|
||||
@@ -158,6 +179,15 @@ type Querier interface {
|
||||
InsertSession(ctx context.Context, arg InsertSessionParams) error
|
||||
InsertUser(ctx context.Context, arg InsertUserParams) error
|
||||
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
|
||||
// One page of the subject's ledger, newest grant first, optionally limited
|
||||
// to one state. Every record query is scoped by the subject, so a caller
|
||||
// never reads or revokes another subject's consent. The state is computed,
|
||||
// never stored: revoked once revoked_at is set; superseded when a newer
|
||||
// unrevoked record of the same subject and purpose exists (never for C4,
|
||||
// whose records are scoped by invitation); active otherwise. The page continues after the (granted_at, id) position of
|
||||
// the last record of the previous page.
|
||||
ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error)
|
||||
ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error)
|
||||
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
|
||||
// Lists the other accounts of a provider that have usage in a month, so
|
||||
// startup can warn about a renamed EMAIL_ACCOUNT.
|
||||
@@ -228,6 +258,13 @@ type Querier interface {
|
||||
// the job did not cause the failure. The same guard as the completion
|
||||
// applies, one (id, attempt) pair per job. It returns the IDs it released.
|
||||
ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error)
|
||||
// Revokes every unrevoked record of a purpose other than C4, superseded ones
|
||||
// included, and returns them. A revocation time before the grant time, from
|
||||
// clock skew between instances, is stamped at the grant time instead.
|
||||
RevokeConsentRecords(ctx context.Context, arg RevokeConsentRecordsParams) ([]RevokeConsentRecordsRow, error)
|
||||
// Revokes every unrevoked C4 record of the subject for one organization and
|
||||
// returns them, with the same clamp of the revocation time as above.
|
||||
RevokeContactConsentRecords(ctx context.Context, arg RevokeContactConsentRecordsParams) ([]RevokeContactConsentRecordsRow, error)
|
||||
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
|
||||
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
|
||||
// Bounds a consumer transaction on the server, local to the transaction.
|
||||
@@ -270,8 +307,11 @@ type Querier interface {
|
||||
// Replaces the registration of an unverified account and advances the
|
||||
// registration version in the same statement, so no caller can choose it.
|
||||
// The version check rejects a writer that read an older row; a verified
|
||||
// account never changes.
|
||||
UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (User, error)
|
||||
// account never changes. The same statement deletes the C1 that the earlier
|
||||
// registration of this account recorded, so the consent of an earlier
|
||||
// registrant never stands for the new one; the new registration records its
|
||||
// own C1 in the same transaction. A version conflict deletes nothing.
|
||||
UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (UpdateUserRegistrationRow, error)
|
||||
}
|
||||
|
||||
var _ Querier = (*Queries)(nil)
|
||||
Reference in new issue
Block a user