feat(identity): confirm registration email atomically

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 09:12:15 +03:00
1 parent 8e7ce8d71c
commit fade4e76e4
75 files changed
+4188 -403

No files matched your search

@@ -52,6 +52,7 @@ SELECT
text_version,
text_hash,
source,
registration_version,
organization_id,
organization_name,
field_set,
@@ -81,6 +82,7 @@ type GetContactConsentRecordByInvitationRow struct {
TextVersion string
TextHash []byte
Source string
RegistrationVersion pgtype.Int8
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
@@ -102,6 +104,7 @@ func (q *Queries) GetContactConsentRecordByInvitation(ctx context.Context, arg G
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.RegistrationVersion,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
@@ -123,6 +126,7 @@ SELECT
text_version,
text_hash,
source,
registration_version,
organization_id,
organization_name,
field_set,
@@ -154,6 +158,7 @@ type GetCurrentConsentRecordRow struct {
TextVersion string
TextHash []byte
Source string
RegistrationVersion pgtype.Int8
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
@@ -176,6 +181,7 @@ func (q *Queries) GetCurrentConsentRecord(ctx context.Context, arg GetCurrentCon
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.RegistrationVersion,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
@@ -234,6 +240,7 @@ SELECT
record.text_version,
record.text_hash,
record.source,
record.registration_version,
record.organization_id,
record.organization_name,
record.field_set,
@@ -277,6 +284,7 @@ type GetUnrevokedConsentRecordByVersionRow struct {
TextVersion string
TextHash []byte
Source string
RegistrationVersion pgtype.Int8
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
@@ -298,6 +306,7 @@ func (q *Queries) GetUnrevokedConsentRecordByVersion(ctx context.Context, arg Ge
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.RegistrationVersion,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
@@ -319,6 +328,7 @@ INSERT INTO consent_records (
text_version,
text_hash,
source,
registration_version,
granted_at
) VALUES (
$1,
@@ -327,7 +337,8 @@ INSERT INTO consent_records (
$4,
$5,
$6,
$7
$7::bigint,
$8
)
ON CONFLICT (subject_id, purpose, text_version)
WHERE revoked_at IS NULL AND purpose <> 'c4'
@@ -339,6 +350,7 @@ RETURNING
text_version,
text_hash,
source,
registration_version,
organization_id,
organization_name,
field_set,
@@ -364,13 +376,14 @@ RETURNING
`
type InsertConsentRecordParams struct {
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
GrantedAt pgtype.Timestamptz
ID pgtype.UUID
SubjectID pgtype.UUID
Purpose string
TextVersion string
TextHash []byte
Source string
RegistrationVersion pgtype.Int8
GrantedAt pgtype.Timestamptz
}
type InsertConsentRecordRow struct {
@@ -380,6 +393,7 @@ type InsertConsentRecordRow struct {
TextVersion string
TextHash []byte
Source string
RegistrationVersion pgtype.Int8
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
@@ -402,6 +416,7 @@ func (q *Queries) InsertConsentRecord(ctx context.Context, arg InsertConsentReco
arg.TextVersion,
arg.TextHash,
arg.Source,
arg.RegistrationVersion,
arg.GrantedAt,
)
var i InsertConsentRecordRow
@@ -412,6 +427,7 @@ func (q *Queries) InsertConsentRecord(ctx context.Context, arg InsertConsentReco
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.RegistrationVersion,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
@@ -433,6 +449,7 @@ INSERT INTO consent_records (
text_version,
text_hash,
source,
registration_version,
organization_id,
organization_name,
field_set,
@@ -446,6 +463,7 @@ INSERT INTO consent_records (
$3,
$4,
'invitation_acceptance',
NULL,
$5,
$6,
$7::text [],
@@ -462,6 +480,7 @@ RETURNING
text_version,
text_hash,
source,
registration_version,
organization_id,
organization_name,
field_set,
@@ -493,6 +512,7 @@ type InsertContactConsentRecordRow struct {
TextVersion string
TextHash []byte
Source string
RegistrationVersion pgtype.Int8
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
@@ -528,6 +548,7 @@ func (q *Queries) InsertContactConsentRecord(ctx context.Context, arg InsertCont
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.RegistrationVersion,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
@@ -550,6 +571,7 @@ WITH ledger AS (
record.text_version,
record.text_hash,
record.source,
record.registration_version,
record.organization_id,
record.organization_name,
record.field_set,
@@ -584,6 +606,7 @@ SELECT
ledger.text_version,
ledger.text_hash,
ledger.source,
ledger.registration_version,
ledger.organization_id,
ledger.organization_name,
ledger.field_set,
@@ -622,6 +645,7 @@ type ListConsentRecordsRow struct {
TextVersion string
TextHash []byte
Source string
RegistrationVersion pgtype.Int8
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
@@ -662,6 +686,7 @@ func (q *Queries) ListConsentRecords(ctx context.Context, arg ListConsentRecords
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.RegistrationVersion,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
@@ -690,6 +715,7 @@ SELECT
text_version,
text_hash,
source,
registration_version,
organization_id,
organization_name,
field_set,
@@ -720,6 +746,7 @@ type ListCurrentContactConsentRecordsRow struct {
TextVersion string
TextHash []byte
Source string
RegistrationVersion pgtype.Int8
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
@@ -747,6 +774,7 @@ func (q *Queries) ListCurrentContactConsentRecords(ctx context.Context, arg List
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.RegistrationVersion,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
@@ -767,6 +795,83 @@ func (q *Queries) ListCurrentContactConsentRecords(ctx context.Context, arg List
return items, nil
}
const lockRegistrationConsentRecord = `-- name: LockRegistrationConsentRecord :one
SELECT
id,
subject_id,
purpose,
text_version,
text_hash,
source,
registration_version,
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 = 'c1'
AND source = 'registration'
AND registration_version = $2
AND revoked_at IS NULL
FOR UPDATE
`
type LockRegistrationConsentRecordParams struct {
SubjectID pgtype.UUID
RegistrationVersion pgtype.Int8
}
type LockRegistrationConsentRecordRow 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
}
// Locks the active registration C1 while its pending registration is applied.
func (q *Queries) LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error) {
row := q.db.QueryRow(ctx, lockRegistrationConsentRecord, arg.SubjectID, arg.RegistrationVersion)
var i LockRegistrationConsentRecordRow
err := row.Scan(
&i.ID,
&i.SubjectID,
&i.Purpose,
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.RegistrationVersion,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
&i.InvitationID,
&i.InvitationTermsVersion,
&i.GrantedAt,
&i.RevokedAt,
&i.RevocationSource,
&i.State,
)
return i, err
}
const revokeConsentRecords = `-- name: RevokeConsentRecords :many
UPDATE consent_records
SET
@@ -784,6 +889,7 @@ RETURNING
text_version,
text_hash,
source,
registration_version,
organization_id,
organization_name,
field_set,
@@ -809,6 +915,7 @@ type RevokeConsentRecordsRow struct {
TextVersion string
TextHash []byte
Source string
RegistrationVersion pgtype.Int8
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
@@ -844,6 +951,7 @@ func (q *Queries) RevokeConsentRecords(ctx context.Context, arg RevokeConsentRec
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.RegistrationVersion,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
@@ -881,6 +989,7 @@ RETURNING
text_version,
text_hash,
source,
registration_version,
organization_id,
organization_name,
field_set,
@@ -906,6 +1015,7 @@ type RevokeContactConsentRecordsRow struct {
TextVersion string
TextHash []byte
Source string
RegistrationVersion pgtype.Int8
OrganizationID pgtype.UUID
OrganizationName pgtype.Text
FieldSet []string
@@ -940,6 +1050,7 @@ func (q *Queries) RevokeContactConsentRecords(ctx context.Context, arg RevokeCon
&i.TextVersion,
&i.TextHash,
&i.Source,
&i.RegistrationVersion,
&i.OrganizationID,
&i.OrganizationName,
&i.FieldSet,
@@ -109,37 +109,146 @@ func (q *Queries) AdvanceUserRegistration(ctx context.Context, arg AdvanceUserRe
return i, err
}
const consumeEmailToken = `-- name: ConsumeEmailToken :one
UPDATE email_tokens AS token
SET consumed_at = $1
FROM users AS owner
const confirmUserEmail = `-- name: ConfirmUserEmail :one
UPDATE users
SET
password_hash = $1,
scenario = $2,
onboarding_step = $3,
email_verified_at = $4,
updated_at = $4,
version = version + 1
WHERE
token.token_hash = $2
AND token.purpose = $3
AND token.consumed_at IS NULL
AND token.invalidated_at IS NULL
AND token.expires_at > $1
AND owner.id = token.user_id
AND owner.registration_version = token.registration_version
id = $5
AND registration_version = $6
AND email_verified_at IS NULL
RETURNING
token.id,
token.user_id,
token.purpose,
token.token_hash,
token.registration_version,
token.created_at,
token.expires_at,
token.consumed_at,
token.invalidated_at,
token.pending_password_hash,
token.pending_scenario,
token.pending_onboarding_step
id,
email,
email_normalized,
password_hash,
scenario,
onboarding_step,
email_verified_at,
registration_version,
last_registered_at,
version,
created_at,
updated_at
`
type ConfirmUserEmailParams struct {
PasswordHash string
Scenario string
OnboardingStep string
VerifiedAt pgtype.Timestamptz
ID pgtype.UUID
RegistrationVersion int64
}
// Applies the registration carried by its token and verifies the address in
// one optimistic update. The caller holds the token lock and checks the
// matching C1 in the same transaction.
func (q *Queries) ConfirmUserEmail(ctx context.Context, arg ConfirmUserEmailParams) (User, error) {
row := q.db.QueryRow(ctx, confirmUserEmail,
arg.PasswordHash,
arg.Scenario,
arg.OnboardingStep,
arg.VerifiedAt,
arg.ID,
arg.RegistrationVersion,
)
var i User
err := row.Scan(
&i.ID,
&i.Email,
&i.EmailNormalized,
&i.PasswordHash,
&i.Scenario,
&i.OnboardingStep,
&i.EmailVerifiedAt,
&i.RegistrationVersion,
&i.LastRegisteredAt,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const consumeEmailToken = `-- name: ConsumeEmailToken :one
WITH candidate AS MATERIALIZED (
SELECT
token.id,
token.user_id,
token.purpose,
token.token_hash,
token.registration_version,
token.created_at,
token.expires_at,
token.pending_password_hash,
token.pending_scenario,
token.pending_onboarding_step
FROM email_tokens AS token
INNER JOIN users AS owner ON owner.id = token.user_id
WHERE
token.token_hash = $1
AND token.purpose = $2
AND token.consumed_at IS NULL
AND token.invalidated_at IS NULL
AND token.expires_at > $3
AND owner.registration_version = token.registration_version
FOR UPDATE OF token
),
consumed AS (
UPDATE email_tokens AS token
SET
consumed_at = $3,
pending_password_hash = NULL,
pending_scenario = NULL,
pending_onboarding_step = NULL
FROM candidate
WHERE token.id = candidate.id
RETURNING token.id, token.consumed_at, token.invalidated_at
)
SELECT
candidate.id,
candidate.user_id,
candidate.purpose,
candidate.token_hash,
candidate.registration_version,
candidate.created_at,
candidate.expires_at,
consumed.consumed_at,
consumed.invalidated_at,
candidate.pending_password_hash,
candidate.pending_scenario,
candidate.pending_onboarding_step
FROM candidate
INNER JOIN consumed ON consumed.id = candidate.id
`
type ConsumeEmailTokenParams struct {
ConsumedAt pgtype.Timestamptz
TokenHash []byte
Purpose string
ConsumedAt pgtype.Timestamptz
}
type ConsumeEmailTokenRow struct {
ID pgtype.UUID
UserID pgtype.UUID
Purpose string
TokenHash []byte
RegistrationVersion int64
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
ConsumedAt pgtype.Timestamptz
InvalidatedAt pgtype.Timestamptz
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
}
// Consumes a token in one statement. Concurrent callers queue on the token
@@ -151,9 +260,9 @@ type ConsumeEmailTokenParams struct {
// The confirmation guarantee therefore needs MarkUserEmailVerified with the
// returned registration version in the same transaction, rolled back when it
// matches no row.
func (q *Queries) ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error) {
row := q.db.QueryRow(ctx, consumeEmailToken, arg.ConsumedAt, arg.TokenHash, arg.Purpose)
var i EmailToken
func (q *Queries) ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, error) {
row := q.db.QueryRow(ctx, consumeEmailToken, arg.TokenHash, arg.Purpose, arg.ConsumedAt)
var i ConsumeEmailTokenRow
err := row.Scan(
&i.ID,
&i.UserID,
@@ -339,6 +448,52 @@ func (q *Queries) GetActiveSessionByTokenHash(ctx context.Context, arg GetActive
return i, err
}
const getEmailTokenByHash = `-- name: GetEmailTokenByHash :one
SELECT
id,
user_id,
purpose,
token_hash,
registration_version,
created_at,
expires_at,
consumed_at,
invalidated_at,
pending_password_hash,
pending_scenario,
pending_onboarding_step
FROM email_tokens
WHERE token_hash = $1
AND purpose = $2
`
type GetEmailTokenByHashParams struct {
TokenHash []byte
Purpose string
}
// Reads a token before password verification; Consume rechecks it in the
// confirmation transaction and clears pending credentials when it succeeds.
func (q *Queries) GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error) {
row := q.db.QueryRow(ctx, getEmailTokenByHash, arg.TokenHash, arg.Purpose)
var i EmailToken
err := row.Scan(
&i.ID,
&i.UserID,
&i.Purpose,
&i.TokenHash,
&i.RegistrationVersion,
&i.CreatedAt,
&i.ExpiresAt,
&i.ConsumedAt,
&i.InvalidatedAt,
&i.PendingPasswordHash,
&i.PendingScenario,
&i.PendingOnboardingStep,
)
return i, err
}
const getEmailTokenState = `-- name: GetEmailTokenState :one
SELECT
token.consumed_at,
@@ -126,6 +126,7 @@ type ConsentRecord struct {
GrantedAt pgtype.Timestamptz
RevokedAt pgtype.Timestamptz
RevocationSource pgtype.Text
RegistrationVersion pgtype.Int8
}
type ConsentText struct {
@@ -78,6 +78,10 @@ type Querier interface {
// the lease owner and the attempt, so a worker that lost its lease cannot
// complete the job.
CompleteScheduledJob(ctx context.Context, arg CompleteScheduledJobParams) (int64, error)
// Applies the registration carried by its token and verifies the address in
// one optimistic update. The caller holds the token lock and checks the
// matching C1 in the same transaction.
ConfirmUserEmail(ctx context.Context, arg ConfirmUserEmailParams) (User, error)
// Consumes a token in one statement. Concurrent callers queue on the token
// row lock; under READ COMMITTED each waiter re-checks the WHERE clause
// against the committed row, so exactly one of them updates it. The join
@@ -87,7 +91,7 @@ type Querier interface {
// The confirmation guarantee therefore needs MarkUserEmailVerified with the
// returned registration version in the same transaction, rolled back when it
// matches no row.
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error)
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, error)
// Counts the hiding records of one candidate for the settings read.
CountCandidateHiddenOrganizations(ctx context.Context, userID pgtype.UUID) (int64, error)
// Counts the families of a category that have at least one published
@@ -171,6 +175,9 @@ type Querier interface {
// version published after it. The unique (policy_key, version) index serves
// the backward scan.
GetEffectivePolicyVersion(ctx context.Context, arg GetEffectivePolicyVersionParams) (PolicyVersion, error)
// Reads a token before password verification; Consume rechecks it in the
// confirmation transaction and clears pending credentials when it succeeds.
GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error)
// Explains why ConsumeEmailToken matched no row.
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
GetLatestAssessmentFamily(ctx context.Context, familyKey string) (AssessmentFamily, error)
@@ -397,6 +404,8 @@ type Querier interface {
// because aggregate writers check the expected version, so scanning without a
// position watermark cannot overtake an earlier version.
LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error)
// Locks the active registration C1 while its pending registration is applied.
LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error)
// Notes that the first request of a claimed delivery is about to start, by the
// database clock, and clears the count of worker failures: the claim and the
// preparation succeeded, so the failures are no longer consecutive. The provider keeps the idempotency key for a window counted